Home > Software design >  Is there a way to detect a stack overflow during runtime? (c )
Is there a way to detect a stack overflow during runtime? (c )

Time:09-17

I have a massive recursive function that can easily overflow a system based on user input, and I wanted to know if there is a way to detect if you are about to run out of callstack space during runtime. Is there a way to check if I am going to blow the stack so I can terminate/do something else if I am about to?

CodePudding user response:

There are cases where we prefer to use recursive function. However, if the recursive function goes too deep in some environments, such as in Visual C code, an unwanted result might occur such as a stack-overflow.Same as yours for that purpose only we convert recursive function into while-loop with stack. You can check implementation here

Actually there is no common way to detect the system stack size because each and every compiler has the different stack size and some of them have adjustable stack size.

You can check different size as follow:

glibc i386, x86_64: 7.4 MB
Tru64 5.1: 5.2 MB
Cygwin: 1.8 MB
Solaris 7..10: 1 MB
MacOS X 10.5: 460 KB
AIX 5: 98 KB
OpenBSD 4.0: 64 KB
HP-UX 11: 16 KB

Since it's runtime error so you can't catch using try-catch statement either but you can implement prevention logic.

#include <stdio.h>

// These will be set at the top of main()
static char * _topOfStack;
static int _maxAllowedStackUsage;

int GetCurrentStackSize()
{
   char localVar;
   int curStackSize = (&localVar)-_topOfStack;
   if (curStackSize < 0) curStackSize = -curStackSize;  // in case the stack is growing down
   return curStackSize;
}

void MyRecursiveFunction()
{
   int curStackSize = GetCurrentStackSize();
   printf("MyRecursiveFunction:  curStackSize=%i\n", curStackSize);

   if (curStackSize < _maxAllowedStackUsage) MyRecursiveFunction();
   else
   {
      printf("    Can't recurse any more, the stack is too big!\n");
   }
}

int main(int, char **)
{
   char topOfStack;
   _topOfStack = &topOfStack;
   _maxAllowedStackUsage = 4096;  // or whatever amount you feel comfortable allowing

   MyRecursiveFunction();
   return 0;
}

CodePudding user response:

Is there a way to detect a stack overflow during runtime? (c )

There is no standard way to know how much stack space is available, nor is there a standard way to know how much stack has been consumed, nor is there a standard way to know how stack a function call would consume.

In conclusion: There is no standard way to detect a potential stack overflow.

  • Related