We are in a situation that have a large application and now there is a situation that would need to know which .so module is allocating how much memory. I have no idea here, I was wondering a custom allocator overriding operator new, but that didn't help because I still cannot trace which module is doing to allocation. Replacing new by custom allocator would be terrible amount of work. Does anyone know how can I tell which module is doing how much allocations ?
2 Answers
It's not easy.
You can hook malloc
, free
, realloc
globally in the application. Corresponding articles on Stackoverflow: How to use __malloc_hook?, An alternative for the deprecated __malloc_hook functionality of glibc.
You can retrieve a caller address from that hooks using __builtin_return_address
and compare it with addresses of shared libraries. Maybe you have to examine a deeper frame address to get a proper address in a library, not an address of libc++. Read this Stackoverflow article __builtin_return_address returns null for index >0?.

- 29,503
- 10
- 41
- 64
You could make use of the LD_PRELOAD
trick to hook malloc
, realloc
, free
etc. That, combined with the info gleaned from boost.stacktrace
would get you most (if not all) of what you need. Not trivial though.

- 12,232
- 2
- 15
- 18
-
that doesn't seem very performant. Is there a way how to preload malloc realloc for each .so module (some different function? ) – Martin Kosicky Apr 08 '20 at 11:52
-
Not as far as I know. At the end f the day there's always going to be *some* performance hit -- you're intercepting calls to malloc etc. and doing extra work around the real call. As for exactly what that hit is and whether or not it's acceptable...? Only testing will tell. – G.M. Apr 08 '20 at 15:14