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
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.
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.
Shortest segfault ever:
*(int*)0=0;
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);
}
char * ptr = 0;
*ptr = 1;
Segmentation fault
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.