On 08/05/2016 12:55 PM, Mark J Twain wrote:
I use malloc to allocate some memory, then free it later. For monitoring
purposes, I would like to know how much is free'ed by free by just
knowing the object. Or, rather, given a ptr allocated by malloc, bet the
block size it allocated from the ptr alone.

Some C compilers have special intrinsics and such for this, does D have
any ability? If not, any hacks? I just need something that works.


malloc stores the allocation size and other information right before the pointer that it returns. You can do better than I do below if you know the exact objects that it stores there. And of course you don't need a struct. I just liked the property idea there. :)

import std.stdio;
import core.stdc.stdlib;

struct AllocatedMemory {
    void *p;

    alias SizeType = size_t;    // perhaps ulong?

    @property SizeType size() {
        return *cast(SizeType*)(p - SizeType.sizeof);
    }
}

void myFree(void * p) {
    auto a = AllocatedMemory(p);
    writefln("Freeing something like 0x%x bytes", a.size);
}

void main() {
    auto p = malloc(0x12345);
    myFree(p);
}

Prints:

Freeing something like 0x12351 bytes

Ali

Reply via email to