Take the 2-minute tour ×

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.

share|improve this question
support.microsoft.com/kb/315937 –  Mooing Duck Aug 27 '12 at 16:59
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
Personally, I find that SO is not something to avoid, but to embrace. Just look at the great community here! –  Brian Cain Aug 27 '12 at 17:01
Modern version of Mooing Duck's link? msdn.microsoft.com/en-us/library/89f73td2.aspx –  Steve-o Aug 27 '12 at 17:18
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

4 Answers 4

up vote 7 down vote accepted

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.

share|improve this answer
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

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.

share|improve this answer
Thanks for these constructive ideas. –  Ralph Tandetzky Aug 28 '12 at 17:13

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.

share|improve this answer
-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

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":
    std::cout << "sp=" << sp << std::endl;

    // call bad code here

    // restore old SP so we can return to OS
        "mov %%eax,%%esp":

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

    delete [] mystack;
    return 0;

This is gcc's assembler syntax.

share|improve this answer
Oops, make that int *top = (mystack + 64*1024 - 1); –  Nathan Andrew Mullenax Aug 27 '12 at 18:04
Probably also re: enough power to shoot oneself in the foot. –  Nathan Andrew Mullenax Aug 27 '12 at 18:15
Ouch! What a hack! –  Ralph Tandetzky Nov 21 '12 at 17:52
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. –  Nathan Adams Sep 14 '13 at 19:20

Your Answer


