'Query regarding memory management in C structures
Suppose there is a struct a with other structs as members
struct a {
struct b* b;
struct c* c;
};
struct a* a1;
Now I allocate memory dynamically to an object of a
a1 = (struct a*) malloc(sizeof(a));
Now I similarly create a new object of struct b
struct b* b1 = (struct b*) malloc(sizeof(b));
Now after some time in code I create a reference for b1 in a1
a1.b = b1;
b1 = NULL;
Later if I free a1, will the memory allocated to b1 also get freed?
free(a1);
Solution 1:[1]
Later if I free a1, will the memory allocated to b1 also get freed
No it will not. The rules are very simple:
- Exactly one
freefor eachmalloc(assuming we do want to free memory) - The address passed to
freemust be exactly what was returned by a previousmalloc.
Here malloc of course applies also to any other allocation function such as calloc, realloc, etc. So in your example the required free calls are:
free(a1.b);
free(a1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kaylum |
