EdgarC EdgarC - 3 years ago 110
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

typedef struct dictionary Dic;

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

dc->next = NULL;

return dc;

Now, if I do something like:

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


void printWord(Dic* dic){

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download