Why can't I cause a seg fault?

前端 未结 10 1698
名媛妹妹
名媛妹妹 2020-12-31 00:24

OK for whatever reason I\'m having trouble causing a seg fault. I want to produce one so that I can use gdb to see how to debug one. I have tried both examples

相关标签:
10条回答
  • 2020-12-31 00:59

    For the first example, the compiler probably put the string in writable memory, so there is no seg fault when trying to change it.

    For the second, the compiler may be optimizing the call away or may be optimizing the call itself away to just a jump (since it is a tail call), meaning the stack isn't actually growing with return addresses for each call, so you could recurse indefinitely.

    But as Neil mentioned in his post, any of these things results in "undefined behavior", so the code is not required at runtime to generate a seg fault.

    0 讨论(0)
  • 2020-12-31 00:59

    The Wikipedia article actually lists three methods (one of which is a null pointer dereference); why didn't you try that one?

    As for why the two examples you tried didn't, well, the correct answer as others have noted is that it's undefined behavior, so anything could happen (which includes not segfaulting). But one could speculate that the reason that the first form didn't fail for you is because your compiler or system is lax about memory protection. As for the second case, a tail-recursive-aware compiler conceivably could optimize the infinitely recursive main loop and not end up overflowing the stack.

    0 讨论(0)
  • 2020-12-31 01:04

    Shortest segfault ever:

    *(int*)0=0;
    
    0 讨论(0)
  • 2020-12-31 01:12

    It impossable to try and reliable do it dereferencing pointers.
    This is because how the application handles memory can vary from compiler to compiler also across the same compiler with different options (debug/release mode handeled differently).

    What you can do is explicitly raise the segfault using a signal:

    #include <signal.h>
    
    int main()
    {
        raise(SIGSEGV);
    }
    
    0 讨论(0)
  • 2020-12-31 01:13
    char * ptr = 0;
    *ptr = 1;
    
    Segmentation fault
    
    0 讨论(0)
  • 2020-12-31 01:16

    Both of the things you do will produce "undefined behaviour" in C++ (well, calling main() is actually explicitly forbidden). There is no guarantee that they will cause seg faults - this will depend on a lot of things, but mostly the platform you are running on, which you haven't specified.

    In fact, any suggested method of causing a seg fault may or may not work. This is because a seg fault is almost always associated with C++'s concept of undefined behaviour.

    0 讨论(0)
提交回复
热议问题