Search code examples
c++stack-overflowundefined-behavior

What does the C++ standard say about stack overflow?


I took a look at the draft C++0x standard, and as far as I can tell there is nothing about stack overflow in there. Searching for "stack overflow" yields no results, and searching for "stack" I've only gotten references to stack unwinding and std::stack. Does that mean that there cannot be a conforming implementation of the C++ standard, since there is no mechanism allowed for handling the error when memory is exhausted by a local object such as a huge local array?

The answers to this question indicate that at least the C standard does not mention stack overflow.

To make the question concrete, consider this program

// Program A
int identity(int a) {
  if (a == 0)
    return 0;
  char hugeArray[1024 * 1024 * 1024]; // 1 GB
  return identity(a - 1) + 1;
}
int main() {
  return f(1024 * 1024 * 1024);
}

and this program

// program B
int main() {
  return 1024 * 1024 * 1024;
}

I think the C++ standard does not allow any C++ implementation to do something observably different on these two programs. In reality program A won't run on any modern machine as it is allocating an exabyte of memory on the stack (imagine the function actually used the huge array so the compiler can't silently remove it to no ill effect). Does the C++ standard allow program A to fail?

Edit: The question is not whether the standard should define what happens on stack overflow, the question is what it says, if anything.


Solution

  • I'm not sure if this is what you're looking for, but in Appendix B of the C++03 ISO standard there's the following notice:

    1. Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.
    2. The limits may constrain quantities that include those described below or others.

    (My emphasis) I take this to mean it is perfectly legal for the compiler to allow one of those functions to work while failing another, provided that the compiler states what limitations are in place and how they are computed from the resources the system has available.