There is no portable solution for this, however, for the environment in which you are interested, there may be specific solutions for the operating system.
For example, with glibc
on Linux, you can use the mallinfo()
function from <malloc.h>
, which returns a struct mallinfo
. The uordblks
and hblkhd
this structure contain the dynamically allocated address space used by the program, including auxiliary service data - if you understand the difference in this before and after each call to malloc()
, you will know the amount of space used by this call. (The overhead is not necessarily constant for every call to malloc()
).
Using your example:
char *myChar; size_t s = sizeof(char); struct mallinfo before, after; int mused; before = mallinfo(); myChar = malloc(s); after = mallinfo(); mused = (after.uordblks - before.uordblks) + (after.hblkhd - before.hblkhd); printf("Requested size %zu, used space %d, overhead %zu\n", s, mused, mused - s);
Indeed, the overhead is likely to be quite negligible unless you make a very large number of very small distributions, which is bad anyway.
source share