I am writing a C program that requires me to use a dynamically allocated struct which is defined as below.

typedef struct
513 {
514     char* word;
515     int freq;
516 }wordfreq;

When I allocate the word field of this struct, I am allocating this dynamically as well (using strdup).

Now when I want to free this struct here's basically what I'm doing

wordfreq* w (its a parameter to a method).
free(w->word);
free(w);

This gives me a glibc double free error at runtime..

If I only use free(w), I don't get an error, but I am afraid that I'm allowing a memory leak to occur.

Any help will be appreciated.. Thanks..

w and w->word are two separate pointers that (as you say) were allocated using two separate calls to the memory manager. Therefore, the code you posted is correct. Make sure you don't call free(w->word) in a loop, or in two different places.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.