Segfault on stack overflow

前端 未结 6 2207
囚心锁ツ
囚心锁ツ 2021-01-04 08:20

Why does the linux kernel generate a segfault on stack overflow? This can make debugging very awkward when alloca in c or fortran creation of temporary arrays overflows. Sur

6条回答
  •  太阳男子
    2021-01-04 08:30

    A stack overflow is a segmentation fault. As in you've broken the given bounds of memory that the you were initially allocated. The stack of of finite size, and you have exceeded it. You can read more about it at wikipedia

    Additionally, one thing I've done for projects in the past is write my own signal handler to segfault (look at man page signal (2)). I usually caught the signal and wrote out "Fatal error has occured" to the console. I did some further stuff with checkpoint flags, and debugging.

    In order to debug segfaults you can run a program in GDB. For example, the following C program will segfault: #segfault.c #include #include

    int main() 
    {
            printf("Starting\n");
            void *foo=malloc(1000);
            memcpy(foo, 0, 100); //this line will segfault
            exit(0);
    }
    

    If I compile it like so:

    gcc -g -o segfault segfault.c 
    

    and then run it like so:

    $ gdb ./segfault
    GNU gdb 6.7.1
    Copyright (C) 2007 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later 
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "i686-pc-linux-gnu"...
    Using host libthread_db library "/lib/libthread_db.so.1".
    (gdb) run
    Starting program: /tmp/segfault 
    Starting
    
    Program received signal SIGSEGV, Segmentation fault.
    0x4ea43cbc in memcpy () from /lib/libc.so.6
    (gdb) bt
    #0  0x4ea43cbc in memcpy () from /lib/libc.so.6
    #1  0x080484cb in main () at segfault.c:8
    (gdb) 
    

    I find out from GDB that there was a segmentation fault on line 8. Of course there are more complex ways of handling stack overflows and other memory errors, but this will suffice.

提交回复
热议问题