Flash Gordon <sp**@flash-gordon.me.ukwri tes:
Malcolm McLean wrote, On 09/09/07 18:02:
>"siddhu" <si***********@ gmail.comwrote in message
news:11******* *************** @57g2000hsv.goo glegroups.com.. .
>>If I do free(p); memory pointed by p is freed and is available for
further allocations in the process.
But how does it decide about how much memory (size) has to to be
freed and make it available for further allocations?
The secret is that a control block exists _before_ the pointer
returned by malloc().
Or after, or somewhere else entirely.
>free() simply subtracts a few bytes to access it.
Only on some systems.
>Not all mallocs work exactly like this, but a vanilla memory
allocation system does.
What you mean is that is how it works on some systems, whilst others
work differently. I don't see food flavourings have to do with it. At
least, I can't find references to a memory allocation system called
"vanilla".
"Vanilla" is obviously a colloquial term for "ordinary".
To the OP, you don't need to know how it knows, all you need to know
is it gets handled for you.
Agreed.
It can be useful, though, to see an example of *how* the size can be
stored. If you're not familiar with memory allocation, being told
that free "just knows" how many bytes to release can be confusing.
That's why the question "How does free know how many bytes to free?"
is a FAQ (7.26, to be precise). Understanding that, *for example*,
the size can be stored just before the allocated chunk, perhaps along
with some other metadata, tells you that there's nothing magical about
it.
But it's also very important to know that that's just one possible
strategy. For example, an implementation that stores all its metadata
(i.e., everything other than the actual allocated chunks of memory) in
a separate location can be more robust in the presence of code that
writes past the end of an allocated object.
(I think K&R has a sample memory allocator; reading that code can be
instructive.)
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"