Timmy
Timmy

Reputation: 81

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.

Upvotes: 1

Views: 105

Answers (3)

wallyk
wallyk

Reputation: 57774

free() is very simple: It frees the memory block passed to it—which must have come from malloc(). It does not do any cascade frees or other cleanup. It also does not NULL the pointer to help catch simple logic errors.

free(foo->bars);
free(foo);
foo = NULL;   /* good idea to do this, unless `foo` is going out of scope soon */

Upvotes: -1

Harry_Potter
Harry_Potter

Reputation: 49

By using this: foo = (fooType *) malloc(sizeof(fooType)); You are actually allocating memory for the struct 'fooType' which just has the pointer to hold the address of the other allocated block of memory )(malloced for barType).

You have to explicitly free each malloced memory. Otherwise, if you use only free(foo). It will cause memory leaks (http://en.wikipedia.org/wiki/Memory_leak)!!

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477040

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...

Upvotes: 5

Related Questions