I have project written in C-language. I need to find out how much Stack(local variables,..) and Heap memory(allocated with malloc) this process is using. So that I can make a decision that whether a particular Microcontroller(currently my controller has 30KB RAM) meet my project’s minimum RAM/Stack/Heap requirements or not.
I tried /proc/pid/smaps. But it is showing minimun 4kB stack even if the file contains only 2 local integer variables.(I think it’s showing Page size or memory range).
top command output is not useful for this requirement.
Is there any tool to find out stack(with moderate accuracy in bytes) used by a process in realtime in the form of variables etc(or atleast maximum value reached in lifetime also fine).(with this later I need to setup CI job for finding these.)
Atleast I could find out heap using malloc wrapper API like below.(don’t know how to find out deallocated memory in a easy way.)
Eg:
void call_malloc(size_t n)
{
usedMem = usedMem + n; // global variable
p= malloc(n);
}
2
Answers
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.
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?
If you run your code with the very basic command
you will get the following type of output. If you focus on the "Maximum resident set size", and consider the values for "Average stack size" and "Average total size" (i.e. stack + heap), would that address your needs?
This is also discussed more expansively here.