For a C++ program that is using a recursive function, how can I evaluate the dynamic stack size occupied by this 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.
Stack space in recursive calls counts too as extra space required by a program. For example : C++ Java. Python3.
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.
when the recursive depth reaches approximately 500000 it seems stack overflow occurs.
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).
#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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With