c++cmemory-managementfreetcmalloc

TCMalloc - get size of allocation for a pointer


Using TCMalloc - given heap allocated object, is there any way to get the allocated size of the object (meaning only the size passed in malloc call)? I'm asking for a "reliable" method (i.e, not going a word size back assuming the allocation size is stored before the pointer)


Solution

  • Since version 1.6, TCMalloc includes:

    size_t tc_malloc_size(void*);
    

    which returns the usable size of the allocation starting at the argument.

    It is identical to the glibc malloc_usable_size (or BSD's malloc_size), and libtcmalloc includes aliases for both of those functions.

    However, it is not necessarily the originally requested size. It may be larger (and usually is). I don't believe that TCMalloc (or most other malloc implementations) retain that metadata, so there is (afaik) neither a reliable nor an unreliable mechanism to time travel back to the original malloc call and inspect the request size.