39

In C++ a stack overflow usually leads to an unrecoverable crash of the program. For programs that need to be really robust, this is an unacceptable behaviour, particularly because stack size is limited. A few questions about how to handle the problem.

  1. Is there a way to prevent stack overflow by a general technique. (A scalable, robust solution, that includes dealing with external libraries eating a lot of stack, etc.)

  2. Is there a way to handle stack overflows in case they occur? Preferably, the stack gets unwound until there's a handler to deal with that kinda issue.

  3. There are languages out there, that have threads with expandable stacks. Is something like that possible in C++?

Any other helpful comments on the solution of the C++ behaviour would be appreciated.

Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
  • 1
    The standard doesn't even mention the stack, you should specify which platform you are targeting; several platforms provide means to intercept the stack overflow or even get a "stack overflow alert" when the stack is almost exhausted. – Matteo Italia Aug 27 '12 at 17:00
  • 18
    Personally, I find that a Stack Overflow is not something to avoid, but to embrace. Just look at the great community here! – Brian Cain Aug 27 '12 at 17:01
  • The only thing it's really worth watching is "stack leaks", where important functions tend to call themselves (or each other) recursively, resulting in "buildup" of program state (I have never actually seen this happen, and suspect that your program would exhibit a large number of other tumors and disorders before this became evident, but that doesn't render it impossible). Maybe also a limit on any recursive functions you're going to be using. – Wug Aug 27 '12 at 17:12
  • 2
    Modern version of Mooing Duck's link? http://msdn.microsoft.com/en-us/library/89f73td2.aspx – Steve-o Aug 27 '12 at 17:18
  • 2
    Use a smart compiler: `gcc -fsplit-stack`, and you are as likely of having a stack overflow as you are to run out of memory. – Matthieu M. Aug 27 '12 at 17:20
  • @Matthieu What does this compiler option do? – Ralph Tandetzky Aug 27 '12 at 18:59
  • 1
    Never found stack overflow to be a problem, (on desktop OS, anyway). It's happened, sure, but only because of a gross cockup on my part, and easily debugged. Compared with the vast majority of really nasty bugs, SO is a non-issue. – Martin James Aug 27 '12 at 20:33
  • 1
    @RalphTandetzky: As the name implies, splits the stack. The idea is that you begin with a small stack and the compiler instruments the runtime to make it grow as you need, possibly discontiguously (as the memory address space goes). Obviously, it may slow down the program a little, I don't exactly by which margin though. I only of gcc supporting this option; Clang + LLVM does not and I never heard about it from MSVC. – Matthieu M. Aug 28 '12 at 06:43
  • @Matthieu Awesome. That's the kind of thing I was looking for. – Ralph Tandetzky Aug 28 '12 at 07:47
  • `StackOverflow` error comes because you are allocating way too big variable/array. You better allocate that big variable/array to heap. –  Mar 16 '18 at 15:46

6 Answers6

34

Handling a stack overflow is not the right solution, instead, you must ensure that your program does not overflow the stack.

Do not allocate large variables on the stack (where what is "large" depends on the program). Ensure that any recursive algorithm terminates after a known maximum depth. If a recursive algorithm may recurse an unknown number of times or a large number of times, either manage the recursion yourself (by maintaining your own dynamically allocated stack) or transform the recursive algorithm into an equivalent iterative algorithm

A program that must be "really robust" will not use third-party or external libraries that "eat a lot of stack."


Note that some platforms do notify a program when a stack overflow occurs and allow the program to handle the error. On Windows, for example, an exception is thrown. This exception is not a C++ exception, though, it is an asynchronous exception. Whereas a C++ exception can only be thrown by a throw statement, an asynchronous exception may be thrown at any time during the execution of a program. This is expected, though, because a stack overflow can occur at any time: any function call or stack allocation may overflow the stack.

The problem is that a stack overflow may cause an asynchronous exception to be thrown even from code that is not expected to throw any exceptions (e.g., from functions marked noexcept or throw() in C++). So, even if you do handle this exception somehow, you have no way of knowing that your program is in a safe state. Therefore, the best way to handle an asynchronous exception is not to handle it at all(*). If one is thrown, it means the program contains a bug.

Other platforms may have similar methods for "handling" a stack overflow error, but any such methods are likely to suffer from the same problem: code that is expected not to cause an error may cause an error.

(*) There are a few very rare exceptions.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Using third-party libraries is often a question of costs. You have to use the WinApi directly or indirectly if you're on Windows in your program at some point. Same on other system. You won't be able to be without third party libraries at all. (You might consider the C++ standard library as third party.) But my point is, if you want to have a super robust program and use third-party libraries to reduce cost, then you might need a way to guarantee that the program does not crash completely by a stack overflow in other libraries. – Ralph Tandetzky Aug 28 '12 at 17:11
  • Can you tell us more about those 'very few rare exception'? – Vishal Sharma Jul 30 '19 at 13:41
10

You can protect against stack overflows using good programming practices, like:

  1. Be very carefull with recursion, I have recently seen a SO resulting from badly written recursive CreateDirectory function, if you are not sure if your code is 100% ok, then add guarding variable that will stop execution after N recursive calls. Or even better dont write recursive functions.
  2. Do not create huge arrays on stack, this might be hidden arrays like a very big array as a class field. Its always better to use vector.
  3. Be very carefull with alloca, especially if it is put into some macro definition. I have seen numerous SO resulting from string conversion macros put into for loops that were using alloca for fast memory allocations.
  4. Make sure your stack size is optimal, this is more important in embeded platforms. If you thread does not do much, then give it small stack, otherwise use larger. I know reservation should only take some address range - not physical memory.

those are the most SO causes I have seen in past few years.

For automatic SO finding you should be able to find some static code analysis tools.

marcinj
  • 48,511
  • 9
  • 79
  • 100
4

Re: expandable stacks. You could give yourself more stack space with something like this:

#include <iostream>

int main()
{
    int sp=0;

    // you probably want this a lot larger
    int *mystack = new int[64*1024];
    int *top = (mystack + 64*1024);

    // Save SP and set SP to our newly created
    // stack frame
    __asm__ ( 
        "mov %%esp,%%eax; mov %%ebx,%%esp":
        "=a"(sp)
        :"b"(top)
        :
        );
    std::cout << "sp=" << sp << std::endl;

    // call bad code here

    // restore old SP so we can return to OS
    __asm__(
        "mov %%eax,%%esp":
        :
        "a"(sp)
        :);

    std::cout << "Done." << std::endl;

    delete [] mystack;
    return 0;
}

This is gcc's assembler syntax.

2

C++ is a powerful language, and with that power comes the ability to shoot yourself in the foot. I'm not aware of any portable mechanism to detect and correct/abort when stack overflow occurs. Certainly any such detection would be implementation-specific. For example g++ provides -fstack-protector to help monitor your stack usage.

In general your best bet is to be proactive in avoiding large stack-based variables and careful with recursive calls.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • `-fstack-protector` doesn't help monitor excess stack allocation. It's for detecting when stack-allocated variables write outside their bounds. – Karl Bielefeldt Aug 27 '12 at 17:38
0

I don't think that that would work. It would be better to push/pop esp than move to a register because you don't know if the compiler will decide to use eax for something.

good
  • 1
  • 2
    Can you mention what "that" refers to in this context? Because the OP doesn't mention/suggest anything specific that may work. – Aditya Patnaik Jan 21 '21 at 07:48
-1

Here ya go: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/resetstkoflw?view=msvc-160

  1. You wouldn't catch the EXCEPTION_STACK_OVERFLOW structured exception yourself because the OS is going to catch it (in Windows' case).
  2. Yes, you can safely recover from an structured exception (called "asynchronous" above) unlike what was indicated above. Windows wouldn't work at all if you couldn't. PAGE_FAULTs are structured exceptions that are recovered from.

I am not as familiar with how things work under Linux and other platforms.

David Bien
  • 622
  • 5
  • 10