Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a stack overflow by monitoring the stack size?

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.

like image 391
c.Chee Avatar asked May 28 '09 05:05

c.Chee


People also ask

How do you prevent stack overflow?

One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Use timer interrupts that periodically check the location of the stack pointer, record the largest value, and watch that it does not grow beyond that value.

How do you monitor a stack?

The stack monitoring is done with the help of Gas Analyzers which are installed at the exhaust point. Now, there are essentially two types of stack monitoring systems. In in-situ measurement system, the emission sensors are placed directly at or inside the stack for emission parameters monitoring.

How do I fix stack overflow?

Solution. The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code that is being recursively called. Once you detect these lines, look for the terminating condition (base condition) for the recursive calls.

How do you detect stack overflow?

A method of detecting stack overflows is to create a canary space at the end of each task. This space is filled with some known data. If this data is ever modified, then the application has written past the end of the stack.


2 Answers

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.

like image 89
swampsjohn Avatar answered Sep 27 '22 15:09

swampsjohn


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.

like image 32
kgiannakakis Avatar answered Sep 27 '22 15:09

kgiannakakis