Warning C6263
Using _alloca in a loop; this can quickly overflow stack
Remarks
This warning indicates that calling _alloca
inside a loop to allocate memory can cause stack overflow. _alloca
allocates memory from the stack, but that memory is only freed when the calling function exits. Stack, even in user-mode, is limited, and failure to commit a page of stack causes a stack overflow exception. The _resetstkoflw
function recovers from a stack overflow condition, allowing a program to continue instead of failing with a fatal exception error. If the _resetstkoflw
function isn't called, there's no guard page after the previous exception. The next time that there's a stack overflow, there are no exceptions at all and the process terminates without warning.
You should avoid calling _alloca
inside a loop if either the allocation size or the iteration count is unknown because it might cause stack overflow. In these cases, consider other options such as heap memory or C++ Standard Library classes.
Code analysis name: USINGALLOCAINLOOP
Example
The following code generates this warning:
#include <windows.h>
#include <malloc.h>
#include <excpt.h>
#include <stdio.h>
#define MAX_SIZE 50
void f ( int size )
{
char* cArray;
__try
{
for(int i = 0; i < MAX_SIZE; i++)
{
cArray = (char *)_alloca(size);
// process cArray...
}
}
__except(GetExceptionCode() == STATUS_STACK_OVERFLOW ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH )
{
// code...
puts("Allocation Failed");
_resetstkoflw();
}
}
The following code uses malloc( ) to correct this warning:
#include <windows.h>
#define MAX_SIZE 50
void f ( int size )
{
char* cArray;
for(int i = 0; i < MAX_SIZE; i++)
{
cArray = (char *) malloc(size);
if (cArray != NULL)
{
// process cArray...
free(cArray);
}
}
}