Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack size dimension ocupied by recursive function

Tags:

c++

For a C++ program that is using a recursive function, how can I evaluate the dynamic stack size occupied by this function?

like image 244
Mihai8 Avatar asked Mar 23 '13 21:03

Mihai8


People also ask

How do you find the stack size of a function?

Count the number of complete strings, multiply by 8 (since "STACK---" is 8 bytes long), and you have the number of bytes of remaining stack space.

What is stack space in recursion?

Stack space in recursive calls counts too as extra space required by a program. For example : C++ Java. Python3.

How is a recursive function related to a stack?

Recursive functions use something called “the call stack.” When a program calls a function, that function goes on top of the call stack. This is similar to a stack of books. You add things one at a time. Then, when you are ready to take something off, you always take off the top item.

How many recursive calls cause a stack overflow?

when the recursive depth reaches approximately 500000 it seems stack overflow occurs.


2 Answers

void recursive_function()
{
  int dummy;
  cout << "stack = " << &dummy << '\n';
  ...
}

Watch the value of &dummy rise as the stack usage goes up (or fall if your stack grows downwards).

like image 118
john Avatar answered Sep 20 '22 23:09

john


#include <stdio.h>
#include <stdlib.h>

ssize_t recurse(int limit, char* stack = NULL)
{
    char dummy;

    if (stack == NULL)
        stack = &dummy;

    if (limit > 0)
        return recurse(limit - 1, stack);
    else
        return stack - &dummy;
}

int main(int argc, char* argv[])
{
    int limit = atoi(argv[1]);
    printf("depth %d took %zd bytes\n", limit, recurse(limit));
    return EXIT_SUCCESS;
}

If I run this with 4 I get:

depth 4 took 192 bytes

As others have suggested in comments, this is not completely portable, but it should work on a fairly wide variety of current systems. Note that the result type is signed in case something "weird" happens--you can surely check it for sanity (say, make sure it's between 5 and 500, depending on what else your function contains).

like image 23
John Zwinck Avatar answered Sep 19 '22 23:09

John Zwinck