In article <db**************************@posting.google.com >,
pembed2003 <pe********@yahoo.com> wrote:
SNIP...
I don't really have the "need" to do that yet but I am wondering how
does 'free' know how many bytes to free? For example:
char* s = malloc(10);
free(s); // how many bytes to free?
How does free know how many bytes to free? I have heard that malloc
also allocate additional memory to hold some header information. Where
is this header information stored? If we have access to the header, we
can find that out?
Thanks!
The answer to that question depends on the implementation of the malloc(),
realloc(), et. all package. Two common implementations are:
1. Have malloc allocate slightly more data than requested and place the
length at the front of the memory block. The pointer that malloc
returns is to the byte just following the length. This method has the
advantage of being very simple to do. However in a virtual memory
system, it frequently requires a page in request in order for free()
to determine the size of the memory block just freed. A rather silly
thing to do if you're not going to modify or otherwise use the page
of memory just read in.
2. Have a "index" page of memory with page addresses and allocation sizes
for those pages. Keep track of which section are allocated using a
bit array on the index page. For example, FreeBSD gets memory in 4K byte
pages. Each page is then used for only allocations of a specified size.
You may have a page that is allocated 16 bytes at a time and used for
any memory request less than or equal to 16 bytes. Another page is
used 32 bytes at a time and handles requests for 17 to 32 bytes. This
pattern continues for 64, 128, 256, ... 4096 bytes. For requests over
4096 bytes, several pages are chained together. When freeing a chunk
of allocated memory, the index page simply needs to have a bit set or
reset so if the allocated memory is paged out, it doesn't need to be
paged back in. Since the index page is frequently accessed, it typically
remains active and isn't paged out.
I am certain that you can think of many more methods of keeping track of
allocated memory. I am also certain that attempting to use internal
implementation information about malloc() and company is the wrong thing to
do and is likely to change from system to system.