0

I am trying to improve the performance of my C++ program and I found that converting memory allocations (mallocs) into object pool is giving great results. The problem is detecting the places from which malloc is called, since the code base is quite large. I can't use simple gdb with break points because there are many timers and signal handlers running in parallel.

Is there a way in gdb using which I can print the entire stack trace whenever malloc is called without having to do it manually each time. OR Can you suggest any other tool which will help me do the same.

user1918858
  • 1,202
  • 1
  • 20
  • 29
  • 4
    How difficult is it to search for string `malloc` in whole codebase? – taskinoor Jul 17 '16 at 08:05
  • Why are you using malloc in C++ code? You should be using new. In which case you can define your own new operators – Ed Heal Jul 17 '16 at 09:34
  • Can you just do [*this*](http://stackoverflow.com/a/378024/23771) in GDB? If it lands in *malloc* (or *new*) you've found a live one. If it doesn't, after 20 or so samples, it uses so little time that optimizing it won't really be worthwhile. – Mike Dunlavey Jul 17 '16 at 18:05
  • @MikeDunlavey it will land on malloc because new uses it.. and I suppose pool uses it too – Swift - Friday Pie Aug 16 '20 at 02:32

2 Answers2

1

You can script gdb using Python.

You can also implement your own malloc function and link with that. The return address will be on the stack, which will give you the caller.

Átila Neves
  • 1,351
  • 11
  • 14
1

The valgrind suite of tools contains massif which you can use for precisely this purpose:

valgrind --tool=massif ./mybinary

This collects details of all allocations including stack traces that you can examine after the program has finished executing. Please see the massif documentation for more details on the output: http://valgrind.org/docs/manual/ms-manual.html. Hope that helps.

P.S. Also checkout the TCMalloc library - it already possibly already does what you want, although you can do better depending on your specific application. The best thing is that no source code changes are needed - you simply replace the malloc function from glibc using a linker directive.

Always Confused
  • 470
  • 4
  • 7