check used stack size using core file

13,080

Solution 1

If you think your stack size limit has been reached due to infinite recursion, an easy way to determine this is to run bt or info stack and see if there are many more frames than you expect. Here's an example where I recursively called a function with around 1024 bytes of local data in each stack frame:

(gdb) info stack
#0  recurse () at loop.c:5
#1  0x0000000000400565 in recurse () at loop.c:5
...
#7939 0x0000000000400565 in recurse () at loop.c:5
#7940 0x000000000040058f in main (argc=1, argv=0x7ffe63afef48) at loop.c:10

You can also exceed the stack size limit with just a few frames if you have a large amount of local data in the frames.

To check the approximate size of the stack, on Linux/x86 you can check the difference between _environ, which contains a high address that's fairly close to the base of the stack, and $sp, the stack pointer in the current frame (top of stack).

(gdb) print (char *)_environ - (char *)$sp
$5 = 8384904

This looks pretty close to the stack size limit of 8MB.

(gdb) shell ulimit -s
8192

You can also look at the difference between the $sp in the frame at the top of the stack and the $sp in the frame at the base of the stack.

(gdb) frame 0
#0  recurse () at loop.c:5
(gdb) set $topsp=$sp
(gdb) frame 7940
#7940 0x000000000040058f in main (argc=1, argv=0x7ffe63afef48) at loop.c:10
(gdb) print (char *)$sp - (char *)$topsp
$6 = 8384640

Solution 2

There is a nifty way to get the stack size in the program.

You can store the address of the first variable in main in a global. Then you can make a function which finds the difference between this address and the current stack address. This will give you the stack size used within 2 bytes.

In main.

char * initaddr;
int main()
{
   char dummy;  // Note -- first variable declared.

   initaddr = &dummy;

   // Other stuff...
}

int stacksize(void)
{
   char dummy2, *lastptr;
   lastptr = &dummy2;

   return(lastptr-initaddr); // This will give the stacksize at the instant of the return function.
}

You can call this function to determine the stacksize used upto that point. This can be used as a debug tool.

Share:
13,080
ashish
Author by

ashish

Updated on June 04, 2022

Comments

  • ashish
    ashish almost 2 years

    I have a core file where the application terminated with SIGSEGV. I suspect this is because the application ran out of stack space. Is there any way to check the used stack size from the core file?

  • Vladimir
    Vladimir almost 8 years
    Firstly wellcome to Stack Overflow. It would be really goodidea to add a tags to your question.
  • ashish
    ashish almost 8 years
    I did find a way using gdb. By checking the difference between the sp register of the starting and ending frame in the backtrace. Seems correct?
  • steve
    steve over 4 years
    How about "aarch64 GNU/Linux"?