skip to Main Content

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


  1. Chosen as BEST ANSWER

    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?


  2. If you run your code with the very basic command

    /usr/bin/time --verbose ${executable}
    

    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?

    Command being timed: "{your_executable}"
    User time (seconds): 0.00
    System time (seconds): 0.01
    Percent of CPU this job got: 90%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.01
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 4032
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 385
    Voluntary context switches: 5
    Involuntary context switches: 84
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0
    

    This is also discussed more expansively here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search