Yusuf Jama Yusuf Jama - 3 months ago 15
C Question

free a dynamically allocated array inside another dynamically allocated array

Say I had the following simple example

#include <stdlib.h>
#include <stdio.h>
struct x {
int* p;

typedef struct y {
x* foo;

void doSomething();

int main() {
return 0;

void doSomething() {
real* tmp = (real*)malloc(sizeof(real));
tmp->foo = (x*)malloc(sizeof(x));

Is it necessary to free the pointer I allocated inside before I free the "outer" allocated memory?

would the second line take care of the first allocated memory...my assumption is no(it will still remain on the heap I assume and I would need to keep it this way).


Just adding my two cents to elaborate on the why part.

Let's state two concepts first.

  1. You need to free()each memory allocated by memory allocator function to avoid memory leak.

  2. You need to pass the exact pointer returned by malloc() or family to free(). They do not have any hierarchical information stored into them (Like, "member of the structure" kind, each allocation is individual).

So, to reach the inner pointer member foo, you must access (dereference) the outer pointer tmp.

Now, if you free() the outer pointer tmp first, afterwards, accessing that free-d memory is invalid invokes undefined behavior. So, you have no way to reach the inner pointer to call free() on it. It remains allocated and contributes to memory leak.

That is why, you have to start freeing the memory from inside out.