Checking stack usage at compile time

shodanex picture shodanex · Sep 24, 2008 · Viewed 10.3k times · Source

Is there a way to know and output the stack size needed by a function at compile time in C ? Here is what I would like to know :

Let's take some function :

void foo(int a) {
    char c[5];
    char * s;
    //do something
    return;
}

When compiling this function, I would like to know how much stack space it will consume whent it is called. This might be useful to detect the on stack declaration of a structure hiding a big buffer.

I am looking for something that would print something like this :

file foo.c : function foo stack usage is n bytes

Is there a way not to look at the generated assembly to know that ? Or a limit that can be set for the compiler ?

Update : I am not trying to avoid runtime stack overflow for a given process, I am looking for a way to find before runtime, if a function stack usage, as determined by the compiler, is available as an output of the compilation process.

Let's put it another way : is it possible to know the size of all the objects local to a function ? I guess compiler optimization won't be my friend, because some variable will disappear but a superior limit is fine.

Answer

Blaisorblade picture Blaisorblade · Jan 12, 2009

Linux kernel code runs on a 4K stack on x86. Hence they care. What they use to check that, is a perl script they wrote, which you may find as scripts/checkstack.pl in a recent kernel tarball (2.6.25 has got it). It runs on the output of objdump, usage documentation is in the initial comment.

I think I already used it for user-space binaries ages ago, and if you know a bit of perl programming, it's easy to fix that if it is broken.

Anyway, what it basically does is to look automatically at GCC's output. And the fact that kernel hackers wrote such a tool means that there is no static way to do it with GCC (or maybe that it was added very recently, but I doubt so).

Btw, with objdump from the mingw project and ActivePerl, or with Cygwin, you should be able to do that also on Windows and also on binaries obtained with other compilers.