Friday 15 March 2013

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



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

let's have next code:

typedef struct { int numbars; bartype *bars; } footype; foo = (footype *) malloc(sizeof(footype)); foo->bars = (bartype *) malloc(sizeof(bartype));

will calling free(foo) free bars or need this:

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

intuitively, sense calling free(foo) should plenty - if don't need phone call free(foo->numbars) shouldn't need phone call free(foo->bars). didn't have manually allocate memory numbars, while did bars.

for every malloc need 1 free. nil done "automatically" you.

note that, contrary claim, not have allocate memory bars, don't have allocate memory numbars. however, are allocating memory *bars.

a single star can create big difference in c...

c malloc free dynamic-memory-allocation dynamic-allocation

No comments:

Post a Comment