The size of the stack size occupied by the recursive function

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

+6
source share
2 answers
void recursive_function() { int dummy; cout << "stack = " << &dummy << '\n'; ... } 

Observe growth &dummy as your stack usage increases (or fall if your stack grows down).

+7
source
 #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 

Like the other comments in the comments, this is not fully portable, but it should work on a fairly wide range of existing systems. Please note that the type of result is signed if something "strange" happens - you can, of course, check it for sanity (say, make sure that it is between 5 and 500, depending on what else contains your function).

+2
source

All Articles