Get size of mem to free by free

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 5 16:19:41 PDT 2016


On 08/05/2016 03:49 PM, H.Loom wrote:
> On Friday, 5 August 2016 at 21:25:41 UTC, Ali Çehreli wrote:
>> malloc stores the allocation size and other information right before
>> the pointer that it returns.
>
> TIL. Is it guaranteed for any malloc implementation ? I'm a bit surpised
> to read that. I thought these kind of trick was only used for aligned
> allocations !

Not guaranteed of course but it's a common technique. Here is an 
implementation:

   https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#1116

As I had suspected, the imprecision in my test code comes from low order 
bits being used as flags (P and M in that source code).

And I think malloc always returns memory properly aligned. After all, 
the user should be able to put anything there.

Ali



More information about the Digitalmars-d-learn mailing list