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,246
  • 8
  • 52
  • 81
static_rtti
  • 50,483
  • 45
  • 130
  • 185

5 Answers5

8

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

nneonneo
  • 162,933
  • 34
  • 285
  • 360
5

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
  • 3,705
  • 6
  • 39
  • 45
Thomas Coudray
  • 104
  • 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,479
  • 11
  • 101
  • 120
2

You can try:

main() {
char *p = NULL;
char c = *p;
}
Stephane Rouberol
  • 4,212
  • 17
  • 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,096
  • 5
  • 30
  • 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