Question

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.

Was it helpful?

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.

OTHER TIPS

On 32-bit computers pointers are four bytes, so one million pointers are four million bytes (on 64-bit machines the size of a pointer is 64 bit, so eight million bytes for your array). Stacks are normally in the range one to four megabytes, so you char array (one million bytes) fits on the stack but the pointer array does not.

It happens because you are running out of stack space. Stack space is a finite per-thread resource; making nested function calls and using local variables consumes it. When you run out, a stack overflow occurs.

Your first example allocates a million char*, which typically would be either 4MB or 8MB of memory. Your second example allocates only 1MB. A typical size for allocated stack space is also around 1MB, so the results are not altogether surprising.

For possible solutions see here or here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top