1ezsla
Last Updated: February 25, 2016
·
1.195K
· stnly
Bf53971e3c0587442c279474d033a799

Segmentation fault

c

The shortest code that will return a segmentation fault (SIGSEGV) but compiles properly with "gcc -Wall -Werror -O"

int main(){return main();}

26 characters.

EDIT:

int main(){goto*0;}

19 characters.

Say Thanks
Respond

8 Responses
Add your response

377
6cd8373fb8a3efe36369a0351726e7d7

Hate to disagree:
int main(){raise(11);}

Or a more standardized version:
#include<signal.h> int main(){raise(SIGSEGV);}

There is also the potential for a good optimizing compiler to convert your tail recursion into loop. Thus potentially sending you into an infinite loop rather than a crash. Theoretically an empty loop (with no side affects) may also be optimized away to make your code do nothing and thus just return.

over 1 year ago ·
406
10534 128567884189 828694189 2287781 3877042 n

@lokiastari: It doesn't compile with gcc -Wall -Werror -O

over 1 year ago ·
408
6cd8373fb8a3efe36369a0351726e7d7

@khasinski :-) Neither did yours until you added int. But you need to resolve the main issue in that your may not actually crash with a good compiler. Using g++-4.2. Examine the output from g++ -Wall -Wextra -Werror -O -S you will see your tail recursion is been converted into a loop. and thus it will never crash. In older versions you may need to up the optimization level but in 4.2 -O is enough.

over 1 year ago ·
409
10534 128567884189 828694189 2287781 3877042 n

It isn't mine ;) I never posted any, I just like @stnly 's post ;)

Nevertheless the post is still true. I haven't found a way to cause a segfault with gcc cranked up with -Wall -Werror -O shorter than

int main(){return main();}
over 1 year ago ·
535
95937f3395dcc5912422cc1606a0bfa3

If you want a segfault and don't care about passing -W* checks, then the symbol 'main' doesn't need to be a function.

int main;

gcc -o segv -c segv.c

over 1 year ago ·
938
241a79c1e1c755973cd248f75b7d0d2d

I think the mac is weird :) I get a Bus error (very similar, but not officially a segfault :) with int main;

over 1 year ago ·
7055
Avatar

Every infinite recurrent function call will end with a segmentation fault :)

over 1 year ago ·
7561
Bf53971e3c0587442c279474d033a799

Wow. I forgot I had this here. Here's one I had going for a while.

int main(){goto*0;}

Enjoy. :)

over 1 year ago ·