Can linux tell if there is a stack overflow?

Remember, I am relatively new to C and Linux.

For one of my classes, I have a project in which we have to find which cities are located in a certain geographic field, we have to use binary search trees, although the implementation is up to us. In my concrete implementation, when I insert a new element into the tree, I recursively call the insert function on the appropriate subtree.

We were also told to test our programs using Valgrind, as any memory leaks or bugs it throws would negatively impact our assessment. My program works fine with the city files we were given up to 100,000, but in 1,000,000 cities Valgrind throws me over a million invalid read / write errors, the stack is full. This does not happen if I run Valgrind with a higher stack size.

When I run the program directly without Valgrind, I don't get any errors. Can linux tell if there is a stack overflow? What would be the consequences of such an overflow?

+3


source to share


2 answers


Why not check it out? In the following program, I sometimes get SIGSEGV

and sometimes not:

#include <stdint.h>

uint64_t pos=261950;

int main(void)
  {
    volatile int a; //just some variables to use the stack
    volatile int b; //and avoid too much optimizations
    a=b; b=a;       
    if(pos) 
      {   
        pos--;
        main();
      }   
    return 0;
  }

      

Valgrind is showing error in all my tests. The value 261950 was found with validation and is likely to be different on a different installation.

This has been tested on GNU / Linux AMD64, Debian 8 without any special tweaks (I haven't disabled anything like ASLR or stack splitting protection). Build command:



gcc -Wall -Wextra 001.c

      

When the variable is pos

larger, I always see a SIGSEGV

-message.

Of course, nothing bad happens here, but you can't be sure how this ends up in a more complex program, so avoid uncontrolled recursion.

+2


source


Can linux tell if a stack overflow has occurred?

No, Linux doesn't care if you overflow your stack. However, it does make some attempt to ensure that off-stack memory addresses are unallocated memory, so a stock overflow is likely to be a segfault. (This depends on the size of each function stack frame; allocating large arrays on the stack can lead to different symptoms if you're out of luck.)



The C runtime probably won't tell you either, because it will require you to insert additional code, which will slow down execution, and then programmers who have taken care of making sure their stacks don't overflow will complain that to pay the cost of protecting your code from your mistakes. This may sound harsh, but this is basically the C design philosophy; if you don't like it, there are other languages ​​as well. However, some compilers allow you to request the addition of additional code (with GCC, see option, see -fstack-check

also -fstack-limit-*

and -fsplit-stack

.)

+2


source







All Articles