Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top