Question:
how to fix stack over flow?
hazel
2009-10-02 06:01:22 UTC
how to fix stack over flow?
Three answers:
toby chung
2009-10-02 06:22:18 UTC
Most likely solution is to stop infinite recursion. In whatever language you are using you have some code like:



myFunction()

{

// do something

myFunction();

}



When the inner call occurs the outer function's context (local variables, etc) are placed on the stack. This occurs again and again until stack is filled. On a modern PC this will take only milliseconds.



The solution is either to avoid the recursion by rewriting the code or have some guard condition based on a parameter passed in.
Paco
2009-10-02 06:18:44 UTC
You haven't given much to go on. Do you have a specific error, or are you asking a theoretical question?



A stack overflow (http://en.wikipedia.org/wiki/Stack_overflow) is a particular kind of buffer overflow (heap overflows being another kind). It typically occurs when you have some variables allocated on the stack (the calling frame for a subroutine) and you write past the bounds of them. For instance, you allocate a 10-character array and then you copy 20 characters into it.



to fix it, you have to do something that doesn't depend on static sizes, or you have to be very careful about the sizes you use.



In C, all the dangerous functions (sprintf, strcpy, strlen) have safe versions. strlen is never safe, but things like sprintf can be replaced with snprintf(). strcpy can be replaced by strncpy. Or memcpy or bcopy can be used. All take a size argument. Therefore, if you know the size of your destination buffer, and you use a function that will never copy more than that size, you should be good.



Get a source code analysis tool like findbugs (or a commercial one like Fortify, Ounce Labs, or Coverity). They can spot the simple stuff really quickly.
Paul
2009-10-02 06:04:22 UTC
Use dynamic memory allocation rather than large local variables.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...