Saturday, 20 April 2013

Error: Stack Overflow

The stack is a part of memory used by your program at run time. It has a predefined size allocated to your program (based on different things like language etc). A stack overflow is when a program uses too much memory from the stack by trying to go outside its allocated area.

The most common reason for this error is infinite recursion:

int function()
{
   return function();
}

Or a deep recursion function that compiles but overflows on use:

void function (argument)
{
    if (condition)
   {
      function (argument.next);
   }
}

Which can be fixed by using stack loops:

stack.push(argument);

while (!stack.empty()) 
{
   argument = stack.pop();

   if (condition)
   {
      stack.push(argument.next);
   }
}

Another possible cause could be by using stupidly large variables, the array below takes up 8 megabytes!

double x[1000000];

Previous examples I've accidentally coded:


Stack overflow caused by infinite recursion:

bool ifCollision()
{
    if(oasisCollision)
   {
   }
}

bool oasisCollision()
{
   if(condition)
   {
       ifCollision();
   }
}

No comments:

Post a Comment