0

I have a function written in C which looks like this

void function1(){
    if(!some_condition){
        function1();
    }
}

This is compiled in gcc on a RedHat linux based machine. Is there a profiling tool that can tell me the maximum amount of stack space used by the code?

piokuc
  • 25,594
  • 11
  • 72
  • 102
hrs
  • 487
  • 5
  • 18
  • It's the number of levels times the size of a stack frame, which is return pointer plus frame pointer plus arguments plus local variables. Of course `some_condition` determines the number of levels. Of course, in this case, since you do nothing after the recursive call, you could transform it into a loop. – Mike Dunlavey Aug 05 '13 at 12:05
  • With which version of GCC and which optimization flags are you compiling? Some recent versions of GCC may *sometimes* optimize tail recursive calls. And show the actual code, not a simplified skeleton! – Basile Starynkevitch Aug 14 '13 at 00:24

1 Answers1

1

Massif from the valgrind suite should tell you this. However, you already know that your program is using the stack too extensively, so I'm not sure using it will help you much.

It seems to me you should refactor your code. Unfortunately, C is not Scheme, and the compilers are not required and don't do any tail recursion optimizations. So it may be a good idea to reorganize your function so it is looping instead of calling itself recursively. Here is a good read on Stacks and Recursion Elimination.

piokuc
  • 25,594
  • 11
  • 72
  • 102
  • Actually i was more interested in deriving an expression for maximum stack usage in my code, but thanks, i would try to eliminate recursion. – hrs Aug 05 '13 at 10:24
  • If I understand correctly, you want to know how much recursion levels your program can handle before crashing. To measure that you can ad a recursion level counter variable to your program, run it in debugger, and see the value of the counter. But this is system dependant, and may differ between systems (they can allow for different stack sizes). Eliminating recursion with iterations doesn't have to be difficult and may get rid of the problem entirely. If you need some help with that then post some more code. – piokuc Aug 05 '13 at 10:31
  • I am interested in calculating the memory requirement for some code. To do this, what i finally did is that i calculated the value of stack pointers at beginning of the program (stack_begin = argv) and at the in the recursive function (stack_end = min(stack_end,&temp_variable)). By this, i now have a rough estimate of the maximum space occupied on the stack. But yes, i am still looking forward to replace recursive calls entirely. Thanks. – hrs Aug 05 '13 at 14:42