1

I have a project written in C language. I want to find stack memory(in the form of local variables etc) consumed by the process(realtime if possible or atleast max value).

With massif, I am able to find exact heap consumption. But i am unable to find exact stack usage. I tried enabling using --stacks=yes (compiled with -g flag). But when I print using ms_print, the stack column is showing random values.

Eg: void main() { int a =10; }

stack value I need should be less than 10.(Considering function return addresses)

273K
  • 29,503
  • 10
  • 41
  • 64
Galaxo
  • 41
  • 5
  • FYI - the stack is a fixed allocation per thread. So unless you are having an actual runtime stack overflow issue, optimizing how much stack space your program uses is not going to be useful. Unless your intent is to compile+link with command line parameters to limit or increase the stack allocation... Are you trying to fix something or is it just a learning exercise? – selbie Dec 12 '22 at 07:54
  • Hi @selbie, My work is to find out different project sanity reports. we made sanity scripts for code coverage(gcov), memory leak(valgrind), code size etc. My new requirement is that "Need to find out RAM requirements, how much Stack & heap exactly my project consuming, so." – Galaxo Dec 12 '22 at 08:38
  • Fair enough. Your stack allocation is a fixed amount per thread. It doesn't matter if your program has a call stack of 100 functions with large arrays or exits from main early after evaluating the command line parameters. Both runs of the program allocated the same amount of stack initially and the stack doesn't really grow (save from being paged in as appropriate). My advice is to ignore the requirement about measuring stack memory and just focus on heap. If you are pressed, lookup what the default stack size is for your compiler/linker and architecture and multiply by max number of threads. – selbie Dec 12 '22 at 09:05
  • IIRC, on Windows it's about 1MB per thread by default unless this overridden by the compiler/linker flags. On Linux, it's initially based on `ulimit -s` environment. But can be overridden at compile/link time as well. – selbie Dec 12 '22 at 09:06

1 Answers1

0

I found reasonable solution.

While compiling use -fstack-usage flag. Eg: gcc -g -fstack-usage filename.c

Use the same in CFLAGS in makefile. No need to run the executable. After compiling the same file name with .su extension will be there in that folder. It can be opened using cat/vim/notepad etc.

It will display "API name -- stack_memory_size". Need to club all .su files and extract the number using script.

For heap memory calculation, simply use valgrind.

PS: While digging more I found below answer. How to determine maximum stack usage in embedded system with gcc?

Galaxo
  • 41
  • 5