chengchunguang
chengchunguang

Reputation: 11

Any method to get the stack size of all functions in a file or a project in C language?

I want to get all functions whose stack size is bigger than the assigned size, is there any easy method to suggest?

Get the .obj file, disassemble it, and then analyze the output file?

Upvotes: 1

Views: 791

Answers (2)

user3458
user3458

Reputation:

Outside of embedded computing, infinite recursion is much more likely culprit in stack overflow than any particular call.

That being said, in the first approximation, look for locally-allocated arrays:

void foo() {
    ...
    char buffer[1024] = "";
    ...
}

Also, don't forget alloca() call - it dynamically allocates space on the stack the same way malloc() allocates it on the heap.

Upvotes: 1

Foo Bah
Foo Bah

Reputation: 26251

You can look at the assembly dump for each function. In gcc, you use the -S option.

Let's say you are interested in the function foo. Then, gcc mangles the function name to _foo. If you take a peek at the assembly, you should see, near the top of the function, an instruction to move the stack pointer. For example, in OSX you have something like:

_foo:
    ...
    movq %rsp, %rbp
    ...
    subq $48, %rsp

That number, $48, is the stack size.

Alternatively, you can look for the equivalent command using nm to find the address where the function starts, ndisasm to give you a human readable dump, and then scanning for the where the stack pointer is moved.

Upvotes: 1

Related Questions