1

I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults.

Is there a simple example program that always segfaults?

idmean
  • 14,540
  • 9
  • 54
  • 83
static_rtti
  • 53,760
  • 47
  • 136
  • 192

5 Answers5

10

main() { *(int *)0xdeadbeef = 37; } should do it.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
8

main;

Is portable, and segfault in 5chars.
It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Source: https://codegolf.stackexchange.com/questions/4399/shortest-code-that-raises-a-sigsegv

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49
Thomas Coudray
  • 134
  • 1
  • 4
  • 2
    Correct, but woefully lacking in any form of explanation as to why it does that (I know why, but not everyone does) – TheSola10 Sep 05 '18 at 15:16
4

try this:

long* ptr = 0x0; //-- you can also use other random values and likely you will segfault
printf("%f", *ptr);
sergio
  • 68,819
  • 11
  • 102
  • 123
2

You can try:

main() {
char *p = NULL;
char c = *p;
}
Stephane Rouberol
  • 4,286
  • 19
  • 18
0

this should die:

int main() {
    char *die;
    printf("%d",(int *)die * 200);
    return 0;
}

edit:

int main() {
    char *die;
    int killer = 200;
    while(1) {
       printf("%d",(int *)die * killer);
       killer = killer * killer;
    }
    return 0;
}
Gung Foo
  • 13,392
  • 5
  • 31
  • 39
  • 1
    Why should it? It's UB, so it might, but it could also just print an arbitrary number. – Daniel Fischer Sep 13 '12 at 11:06
  • Ah, doesn't even compile with gcc. You'd have to explicitly convert the `char*` to an integer for it to compile (wasn't sure whether the compiler permitted an implicit conversion, the standard doesn't, but I think only a diagnostic is required, not termination of the compilation). – Daniel Fischer Sep 13 '12 at 11:15
  • Now it's still UB since you're using the indeterminate value of the uninitialised pointer, but I don't know of any implementation where that would actually crash. What is the idea how you want to cause a crash? – Daniel Fischer Sep 13 '12 at 11:20
  • Then you should probably dereference the pointer in some place. – Daniel Fischer Sep 13 '12 at 11:23