I'm working with two structs:
typedef struct ListNode{
void* value;
struct ListNode *next;
struct ListNode *prev;
} Node;
typedef struct List{
Node *first;
Node *last;
int count;
} List;
Then i declare these variable and allocate memory
List *x = calloc(1,sizeof(List));
Node *x1 = malloc(sizeof(Node));
Node *x2 = malloc(sizeof(Node));
x->first = x1;
x->last =x2;
x->count = 2;
free(x);
So i'm pretty sure that if i free x
, the x->count
, x->first
, x->last
will also disappear as well. However, in this case ,i use gdb to check, and surprisingly only the first element of x is removed (e.g: if in the struct List
i put count on the top, then it will remove only count and leave the rest intact). Why is this happening, and how do i free()
the whole struct?
Your assumption is wrong. If you do free(x)
you're only freeing the block of memory holding the contents of x
, but since this block contains some pointers to other blocks, you will need to free()
those first. This is because free()
does not care about the content of the memory you're freeing, it doesn't do anything fancy. If you see some value modified after using free()
, it's just because free()
uses that memory to store some useful internal values to keep track of memory usage, and it's only a coincidence if that happens to "clear" a pointer in your struct.
The correct way to free()
your struct is the following:
free(x->first);
free(x->last);
// DO NOT free(x->count), it's an integer, not a previously allocated pointer!
free(x);
Here's a visual representation (pardon my awful handwriting):