Search code examples
c++visual-studio-2012constantsstack-overflowcppunit

Const char declaration causes stack overflow


In my VC++ CPPUNIT project the following code in a unit test causes a stack overflow exception:

const int n = 1000000;
const char *test[n];

First-chance exception at 0x00AD89E7 in Utilities_Tests.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00132000). Unhandled exception at 0x00AD89E7 in Utilities_Tests.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00132000).

But this does not:

const int n = 1000000;
char test[n];

The stack overflow happens before the code is executed, thus a breakpoint at the top of the unit test will not be hit. Any idea why this happens? I have the workaround but I'm just curious what's happening.


Solution

  • A char is 1 byte, a char* is, most likely, 4 bytes (can be more, can be less).

    So the first case attempts to allocate more memory (~4 times more) an the stack. Stack memory is limited, it just happens that 1000000 bytes fit on your platform on the stack, but 4 * 1000000 don't.