Home > Software engineering >  Query regarding memory management in C structures
Query regarding memory management in C structures

Time:04-06

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);

CodePudding user response:

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 free for each malloc (assuming we do want to free memory)
  • The address passed to free must be exactly what was returned by a previous malloc.

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);
  • Related