0

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)

Daniel Heilper
  • 1,182
  • 2
  • 17
  • 34
  • Why do you need this? There is no such thing forn the standard `malloc` either? – Jabberwocky Mar 14 '18 at 15:30
  • @Michael Walz - I don't think it is important why I need this. Also, TCMalloc is much more comprehensive library than standard malloc, and it has also heap profiling tool, etc... – Daniel Heilper Mar 14 '18 at 15:34
  • The "why" is often important (See this: http://xyproblem.info/) – Jabberwocky Mar 14 '18 at 15:38
  • @Michael Walz - allocation counting for requests, when each request exclusively owns a group of threads. Each request is inspected once in a while to see if it satisfies memory constraints. The Idea is to Proxy the existing malloc/free calls with a minimal management of a counter per request. When malloc is called the size is trivially known, but not when free is called – Daniel Heilper Mar 14 '18 at 15:46
  • You could write your own `mymalloc/myfree` functions that call the original `malloc/free` or `TCMalloc/free` or what ever, and store the allocated size before the actual data. But this adds a little overhead. – Jabberwocky Mar 14 '18 at 16:02
  • @Michael Walz I'm trying to avoid any overhead in management. Your idea is a well-known approach, however, it can cause serious fragmentations (and performance degradations) if calling malloc of multiple of page size. – Daniel Heilper Mar 14 '18 at 16:06

1 Answers1

4

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.

rici
  • 234,347
  • 28
  • 237
  • 341
  • I tried it, with calling malloc_usable_size, and it seems to have alias to tc_malloc_size (I cannot call directly to tc_XX api since the library is preloaded). – Daniel Heilper Mar 15 '18 at 13:06