Search code examples
cmallocfreedynamic-memory-allocationdynamic-allocation

What is the scope of free() in dynamically allocated memory?


Let's say I have the following code:

typedef struct {
  int numBars;
  BarType *bars;
} fooType;

foo = (fooType *) malloc(sizeof(fooType));
foo->bars = (BarType *) malloc(sizeof(barType));

Will calling free(foo) also free the bars or do I need to do this:

free(foo->bars);
free(foo);

Intuitively, I feel that calling free(foo) should be enough - if I don't need to call free(foo->numBars) I shouldn't need to call free(foo->bars). But I didn't have to manually allocate memory for numBars, while I did for bars.


Solution

  • For every malloc you need one free. Nothing is done "automatically" for you.

    Note that, contrary to your claim, you do not actually have to allocate any memory for bars, just as you don't have to allocate memory for numBars. However, you are allocating memory for *bars.

    A single star can make a big difference in C...