EdgarC EdgarC - 1 month ago 13
C Question

Issue regarding memory allocation in C

For some reason, I cannot manage to correctly free the structure I created, which goes as follows:

struct dictionary{

char word[50]; // Word to be described
char definition[150]; // Definition of said word
struct dictionary* next; // Linked list structure

}*dic;
typedef struct dictionary Dic;

Dic* newWord(char word[], char definition[]){
Dic* dc;
dc = malloc(sizeof(*dic));

strcpy(dc->word,word);
strcpy(dc->definition,definition);
dc->next = NULL;

return dc;
}


Now, if I do something like:

dc = newWord("Word","definition");
free(dc);
printWord(dc);


where:

void printWord(Dic* dic){
if(dic){
printf("<%s>\n",dic->word);
printf(".%s\n",dic->definition);
}
}


will result in no word being printed, yet the definition still being printed, which I can only assume means I'm not properly freeing this structure's memory. How do I go by properly doing it?

Answer

You are using a pointer after freeing it. This is undefined behavior, which means the C compiler can do whatever it wants. It can crash, it can appear to behave properly, or it can do anything in between. Calling free on a pointer doesn't set it to NULL, it releases your claim on the memory, but you have to set it to NULL yourself.

Comments