Segmentation Fault

What is the shortest code that will return a segmentation fault (SIGSEGV) but compiles properly with gcc -Wall -Werror -O?

int main(){return main();}

26 characters.

Update

I found a better one.

int main(){goto*0;}

19 characters.

Why the first one crashes

Every function call pushes a new frame onto the stack: the return address, saved registers, whatever the function needs. main calls itself with no base case, so the frames pile up and the stack grows down until it hits the guard page the kernel placed there for this purpose. The CPU touches an unmapped page, the kernel delivers SIGSEGV (signal 11), and the shell reports exit code 139, which is 128 plus the signal number.

There is a subtlety with -O. A self call in return position is a tail call, and gcc can rewrite tail calls into jumps, which would turn this program into an infinite loop with a flat stack. On gcc 12 with plain -O it still segfaults, I checked while writing this. What changed in modern gcc is the warning: gcc 12 gained -Winfinite-recursion, so gcc -Wall -Werror -O now rejects the program at compile time instead of letting it through to crash. In 2012 it compiled and crashed. Today you have to drop -Werror to get the crash.

Why the second one is better

goto *0 is a computed goto, a GNU extension where the operand is an expression that evaluates to an address, not a label. The program jumps to address 0, which is never mapped, so the instruction pointer itself lands on an unmapped page and the kernel kills the process before it executes anything.

The first program has to walk the stack down page by page until it reaches the guard. The second one faults on its first and only instruction. Same signal, a fraction of the work, and seven fewer characters.