Last Updated: September 27, 2021
·
2.009K
· stnly

Segmentation fault

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.

8 Responses
Add your response

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 ·

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

over 1 year ago ·

@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 ·

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 ·

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 ·

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 ·

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

over 1 year ago ·

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 ·