42

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.

10
  • 21
    Personally, I find that a Stack Overflow is not something to avoid, but to embrace. Just look at the great community here! Commented Aug 27, 2012 at 17:01
  • 2
    Modern version of Mooing Duck's link? msdn.microsoft.com/en-us/library/89f73td2.aspx Commented Aug 27, 2012 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. Commented Aug 27, 2012 at 17:20
  • 2
    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. Commented Aug 27, 2012 at 20:33
  • 2
    @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. Commented Aug 28, 2012 at 6:43

6 Answers 6

37

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Can you tell us more about those 'very few rare exception'?
11

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

  1. Be very careful 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% okay, then add guarding variable that will stop execution after N recursive calls. Or even better don't 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 careful 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 embedded 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 common SO causes I have seen in the past few years.

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

Comments

5

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.

3 Comments

Oops, make that int *top = (mystack + 64*1024 - 1);
Probably also re: enough power to shoot oneself in the foot.
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.
3

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.

1 Comment

-fstack-protector doesn't help monitor excess stack allocation. It's for detecting when stack-allocated variables write outside their bounds.
1

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.

1 Comment

Can you mention what "that" refers to in this context? Because the OP doesn't mention/suggest anything specific that may work.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.