I’m debugging a rather weird stack overflow supposedly caused by allocating too large variables on stack and I’d like to clarify the following.
Suppose I have the following function:
void function()
{
char buffer[1 * 1024];
if( condition ) {
char buffer[1 * 1024];
doSomething( buffer, sizeof( buffer ) );
} else {
char buffer[512 * 1024];
doSomething( buffer, sizeof( buffer ) );
}
}
I understand, that it’s compiler-dependent and also depends on what optimizer decides, but what is the typical strategy for allocating memory for those local variables?
Will the worst case (1 + 512 kilobytes) be allocated immediately once function is entered or will 1 kilobyte be allocated first, then depending on condition either 1 or 512 kilobytes be additionally allocated?
Your local (stack) variables are allocated in the same space as stack frames. When the function is called, the stack pointer is changed to “make room” for the stack frame. It’s typically done in a single call. If you consume the stack with local variables, you’ll encounter a stack overflow.
~512 kbytes is really too large for the stack in any case; you should allocate this on the heap using
std::vector.