Some Linux code is calling malloc in 100 places and I need to know how big any one chunk is. Normally I'd just record these sizes in a my_malloc function but I'm not allowed to do that in this instance. Is there any way to ask the malloc subsystem to provide chunk size for a malloc'd pointer?
Asked
Active
Viewed 1,377 times
1
-
A closely related question: http://stackoverflow.com/questions/5451104/how-to-get-memory-block-length-after-malloc – John Carter Aug 24 '11 at 14:21
3 Answers
3
Your best bet is to use the LD_PRELOAD trick to intercept calls to malloc (definition here). You do not even need to recompile your source code.
Depending on what you are trying to discover, Google Perftools might be useful as well.
-
1I had to google a bit to find out what the LD_PRELOAD trick _is_, please link http://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick in your answer too :) – Kimvais Aug 23 '11 at 18:37
-
@Kimvais: Well, I linked to sample code, figuring that is always better than a one-sentence definition :-). OK I have also added a link to the other SO question. – Nemo Aug 23 '11 at 18:44
-
thanks. I guess I'm just the kind of person who thinks _how does it work_ is much more interesting question than _what does it do_ :) – Kimvais Aug 24 '11 at 04:28
1
*((size_t *)ptr - 1) & ~7
/me covers.

ninjalj
- 42,493
- 9
- 106
- 148
-
1Ouch. Not sure that will work on 64-bit systems. And I am almost certain it will not work for a malloc() of more than 128k or so (for which glibc will use mmap). But nice idea for a quick hack :-). – Nemo Aug 23 '11 at 18:24
-
And seriously, `int` for a size? Jesus. `*((size_t *)ptr - 1) & ~8` at least. – Chris Lutz Aug 23 '11 at 18:38
-
-
That is *entirely* non-portable. The language standard says nothing about how the malloc subsystem stores the sizes of allocated objects -- or even that it does so. For example, `malloc(57)` might allocate 64 bytes and keep no record of the original size. Or the size might not be stored explicitly at all, as long as there's enough information for `realloc` and `free` to work. – Keith Thompson Aug 24 '11 at 14:39
0
Unfortunately, there is no way to do that.

Daniel
- 6,595
- 9
- 38
- 70
-
There is no *portable* way to do that, but a non-portable hack might be good enough if the goal is to debug a problem. – Keith Thompson Aug 24 '11 at 14:40