views:

350

answers:

2

Many C/C++/Fortran and other programmers would have come across "stack overflow" errors. My question is, Is there a tool, a program or a simple code snippet, that allow us to monitor or check the size of the stack while the program is running? This may be helpful to pinpoint where the stack is being accumulated and eventually causing overflow

+2  A: 

Have a look at this question. The accepted answer cites Raymond Chen:

If you have to ask, you're probably doing something wrong.

If you definitely need to do it, then the solution/tool will be platform dependent. One easy trick is to fill the stack with a known byte value (e.g. AA) and monitor the position of the first byte that doesn't have this value. This will give you the maximum stack size used, not the current stack size.

kgiannakakis
I agree. For example, the DSP/BIOS operating system fills a newly allocated stack with the pattern 0xDEADBEEF and uses it to track stack usage.An alternative method on an x86 processor (not easily implemented, has to be done by the OS) would be to put the stack on a separate segment. The OS can then setup the segment descriptor to the allocated length so that an overflow would cause a GPF, at which point the stack contents would be moved up and extended. Not sure if anyone would actually implement this though !
Gautham Ganapathy
A: 

I don't know if there is a program that'll do it for you, but you can easily check inside a function where the stack pointer is (at least in C and C++). Just look at the memory location of any variable. It won't be the exact location, but should be within a few bytes (which is fine for your purposes), since local variables are defined on the stack. If you want the exact value you can get that through assembly I believe.

It might be easier to just look at the stack trace when the program crashes, though.

swampsjohn
and, if you store the address of a local variable from the lowest stack frame (main()) in a globally accessible variable, call it "g_my_stack_base" you can then check approximate stack sizes in any function with approx_stack_size = my_local_function_variable - g_my_stack_base. Ugly but works. Make sure to use char * pointers so the pointer arithmetic returns bytes.
tucuxi