Search code examples
c++memorystack-overflow

Finding out which object/array uses most stack memory


How can I find out which array/object/etc is the most gluttonous user of the stack memory?


Note : below is the original context to the question. Since then, I realised I had severe misunderstandings on how the stack works.

I have a bugged program that ends in a segfault. The segfault is caused by a variable being overwritten with non-sensical values out of the blue… That variable is in stack memory.

Hence my understanding is that I have an overflow of the stack memory at some other point of the program that corrupts the values of variables in the beginning of the next stack memory buffer.

However, valgrind doesn't show any error/warning (when launched with --leak-checks=yes) before encountering the segfault.

Hence a solution would be to find which objects/arrays/etc uses most of the stack memory and move them to heap memory.


Solution

  • If you're developing on a Mac, then you can use Instruments, which has a memory profiler that tells you where memory was allocate it and aggregates based on that.

    Otherwise, you can use valgrind's Massif tool

    If you're on a Mac you can use Instruments. Otherwise you can try using Massif. Sample output from the Massif manual:

    --------------------------------------------------------------------------------
      n        time(B)         total(B)   useful-heap(B) extra-heap(B)    stacks(B)
    --------------------------------------------------------------------------------
     10         10,080           10,080           10,000            80            0
     11         12,088           12,088           12,000            88            0
     12         16,096           16,096           16,000            96            0
     13         20,104           20,104           20,000           104            0
     14         20,104           20,104           20,000           104            0
    99.48% (20,000B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
    ->49.74% (10,000B) 0x804841A: main (example.c:20)
    | 
    ->39.79% (8,000B) 0x80483C2: g (example.c:5)
    | ->19.90% (4,000B) 0x80483E2: f (example.c:11)
    | | ->19.90% (4,000B) 0x8048431: main (example.c:23)
    | |   
    | ->19.90% (4,000B) 0x8048436: main (example.c:25)
    |   
    ->09.95% (2,000B) 0x80483DA: f (example.c:10)
      ->09.95% (2,000B) 0x8048431: main (example.c:23)