memory allocation with malloc

Giorgos Keramidas keramida at ceid.upatras.gr
Tue Aug 5 06:58:57 UTC 2008


On Tue, 5 Aug 2008 11:46:06 +0530, "Shyamal Shukla" <shyamalshukla at gmail.com> wrote:
> Hi All,
>
> I am trying to validate my understanding of how malloc works by means
> of the below C program which tries to corrupt essential information
> maintained by malloc for free() operation.
>
> The program allocates 4, 12 byte blocks (internally 16 bytes are allocated
> for each 12 byte block). Hence the total allocated space was 48 bytes.
>
> As malloc maintains the (length of allocated block + 1), 4 bytes before the
> returned pointer (from malloc), I have manipulated this length for the first
> block and set it to 49 with the goal that a single free shall release all
> these 4 blocks and a subsequent malloc of 15 bytes shall be from the address
> of first block.
>
> However, this does not happen. Can someone please correct my understanding
> and provide me with a reference to the working of malloc() and free()?

That's because the original assumption is false.  You wrote that "malloc
maintains the (length of allocated block + 1), 4 bytes before the
returned pointer (from malloc)".  But that is not really true for all
malloc() implementations, and it certainly isn't true for the `jemalloc'
implementation that FreeBSD 7.X and 8.0-CURRENT use.



More information about the freebsd-questions mailing list