How to Detect Possible/Potential Stack Overflow Problems in a C/C++ Program

Detecting stack overflows during runtime beforehand

Heres a simple solution that works for win-32. Actually resembles what Wossname already posted but less icky :)

unsigned int get_stack_address( void )
{
unsigned int r = 0;
__asm mov dword ptr [r], esp;
return r;
}
void rec( int x, const unsigned int begin_address )
{
// here just put 100 000 bytes of memory
if ( begin_address - get_stack_address() > 100000 )
{
//std::cout << "Recursion level " << x << " stack too high" << std::endl;
return;
}
rec( x + 1, begin_address );
}
int main( void )
{
int x = 0;
rec(x,get_stack_address());
}

Finding potential stack overflow issues in templates

One approach is to use static_assert on the size of the element inside the template code, like this:

static_assert(sizeof(TYPE) < 16384, "Object is too large for the stack");
TYPE Temp = newElement;

This would break a compile in every place where the template is instantiated with a type that is too large for the stack.



Related Topics



Leave a reply



Submit