I’m experiencing a weird problem with C today. Have a quick look at this simplified code snippet:
typedef struct
{
/* The number of index terms */
int nTerms;
/* Information about each index term */
TERMINFO *terms;
} INDEX;
INDEX *buildIndex(char *termsfile, char *dirs[], int n, OPTIONS opts)
{
INDEX *ind = NULL;
ind->nTerms = 5;
return ind;
}
int main(int argc, char *argv[]) {
... // declare and assign values for TERMFILE, DIRS and opts.
INDEX *ind = buildIndex(TERMFILE, DIRS, sizeof(DIRS), opts); // LINE A
printf("Does NOT print %d\n",ind->nTerms); // LINE B
printf("Does NOT print as well"); // LINE C
return 0;
}
When I compile this program, there is no errors occurred, however when I run the compiled file, it doesn’t print anything to the commmand-line (I’m using PuTTy on Windows machine). It becomes even weird when I remove the line LINE A and LINE B, then LINE C can be printed.
In short, whatever goes after LINE A can’t be printed out (or executed?).
I don’t know if there is any problem with my code.
On the second line you are dereferencing a
NULLpointer, which leads to undefined behaviour:You need to make
indpoint to non-local memory, i.e. allocate it from the heap withmalloc, or set it to point to a variable with global lifetime:The responsibility for freeing the returned struct (and not dereferencing it if it’s NULL) is delegated to the caller in this case.
Note that if you were to set
indto point to a locally-declared variable and return it, UB will occur whenever the caller attempts to dereference the pointer, because the stack is restored after the function terminates.