Crashy crashy

We’ve been playing Golf at work, except that we allow languages other than Perl. Today’s challenge has been simple: cause a segfault.

The only way we could think of in perl was:

kill SEGV=>$$;

Which is actually pretty compact, although it’s not a real segfault. The classic segfault in C is:

*(int*)0=0;

So the logical first try is:

main(){*(int*)0=0;}

But I figured that was a bit verbose, and got it down to:

*i=0;main(){*i=0;}

Which shaves a character off because of C’s default of typing everything as an int. You can shave a further two characters thus:

*i;main(){*i=0;}

But that’s not guaranteed – it depends on how i is initialised. Then Graham hit on a brainwave: since functions are just pointers to a place in memory in C, and all the C runtime libs do is transfer control to main, you can cause a crash very simply with:

main=0;

The C runtime tries to transfer control to 0 and crashes – this is probably technically a protection error, but it still shows up as a segfault. Therefore, using the technique from my unguaranteed code above, we get:

main;

And we think that’s as far as you can go. Any advance on that? Using -D on the command line is, of course, cheating…

Comments are closed.