PDA

View Full Version : another malloc question



Ian
10-15-2001, 02:56 PM
ok, here goes...
If I have fp = malloc(3*sizeof(int)); fp now points to the memory address of the first int of 3 that have been allocated for my use. When I use free(fp); it frees those 3 ints.

How does it know that 3 ints worth of space need to be freed? All I passed in was a pointer to the first one. Is there some sort of marker in memory that says this is where a set of allocated memory ends? Or is this kept track of somewhere else?

i.e. if I were to advance the pointer by one int fp = fp+sizeof(int); and then free(fp); would the 2 remaining ints be freed? or would 3 ints be freed? or would I get some sort of error?

sorry I don't understand malloc yet, thanks for any help,

(: Ian

Nick
10-16-2001, 10:18 AM
I know that malloc uses the brk system call.
Ofcourse you can read the source code.

Salem
10-16-2001, 11:43 AM
What malloc hides from you is a linked list of allocated blocks, and a linked list of free blocks.

Each node in each of these lists is a pointer to the block, and the size of the block.

So when you free a block, it looks for the correct pointer (through the allocated list), then moves that to the free list (along with its size).

That's the basics - actual implementations vary (like they will try and merge adjacent free blocks into one larger block).

Troll_King
10-16-2001, 02:35 PM
if I were to advance the pointer by one int fp = fp+sizeof(int); and then free(fp); would the 2 remaining ints be freed? or would 3 ints be freed? or would I get some sort of error?


Error.

Ian
10-16-2001, 08:46 PM
Thanks for all the input guys, it makes a lot more sense to me now.


(: Ian