views:

67

answers:

2

I am using a variable-sized C struct, as follows:

typedef struct {  
  int num_elems;  
  int elem1;  
} mystruct;  
// say I have 5 elements I would like to hold.  
mystruct * ms = malloc(sizeof(mystruct) + (5-1) * sizeof(int));  
ms->num_elems = 5;  
// ... assign 5 elems and use struct  
free(ms);

Will this last free() free everything that was malloc'd, or only sizeof(mystruct)?

+3  A: 

Yes. This will free the whole block that was allocated using malloc.

If you allocate a single block of memory using malloc (like you do in your example), then you need to call free exactly once to free that entire block.

James McNellis
Thanks! I was wondering, since I don't know the exact internals of free and I realized sizeof(*ms) does not adapt to how much space was actually allocated for ms. Your answer explains it all.
Alex
+2  A: 

One thing to be careful of when doing this sort of thing is that the allocation record, used by free to determine what memory to deallocate, is created by malloc and associated with the address malloc returns.

What this means is that you can call free on any pointer pointing to the first byte of the malloc'd block and it will deallocate the correct block of memory, but if you call free on any address in the block other than the first byte, you will at best SIGSEV or SIGBUS, and at worst corrupt the allocation tables, leading to bizarre and inexplicable behaviour.

So if you have block allocated mystruct's like this, be careful not to mix them with single-allocated mystructs, or you will find yourself faced with the nasty choice between leaking memory and corrupting it.

Recurse