0

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..

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Narue
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.