Why can't I cause a seg fault?

Viewed 16243

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 from the Wikipedia article yet neither work.

The first one:

char *s = "Hello World!";
*s = 'H';

And the second example:

int main(void) 
{
    main();
}

EDIT: I'm using Ubutnu 9.10 and g++ as my compiler. Can anyone show me some code that is guaranteed to segfault?

10 Answers

It impossible 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 handled differently).

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

#include <signal.h>

int main()
{
    raise(SIGSEGV);
}

My one line flavor:

*(char *)0 = 0;

Shortest segfault ever:

*(int*)0=0;

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.

int *hello = NULL;
printf(*hello);

or you can define a struct (say HelloWorld struct)

HelloWorld *myWorld = NULL;
myWorld->world = "hello";

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.

char * ptr = 0;
*ptr = 1;

Segmentation fault

Lots of ways to generate a segfault.

Like dereferencing a bad pointer:

char *s = (char *)0xDEADBEEF;
*s = 'a';

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.

If you try to concatenate two constants... you'll get one... at least is a simple way...

strcat("a", "b");

=)

Related