The Shortest Crashing C Program

It might seem like a strange idea to want to write a small crashing C program, but in one of the courses that I’ve been teaching labs this is one of the tasks! It’s actually a very educational thing to do.

Usually students either try to dereference an invalid address, or divide by zero. Dividing by zero raises the SIGFPE signal (Floating Point Exception). Here is a small example program that crashes using divide-by-zero:

int main()
{
    return 1/0;
}

We could remove the return keyword but gcc refuses to generate code for the statement when I do this, even with optimization disabled. We can shave off a few characters from the above by transforming the statement into an assignment:

i;
int main()
{
    i=1/0;
}

Note that I have declared i without a type. This works in C89 because declarations have the implicit type int. In C99 and some other C variants this is an error. Let’s assume we’re writing C89 code, then we can even use implicit int for main:

i;
main()
{
    i=1/0;
}

That’s pretty short – 16 characters if we don’t count redundant whitespace. However, we can do better!

When a C program is compiled, the compiler creates one or more object files with symbolic references to libraries and global objects (functions and variables). The object files are then linked – symbolic references replaced by addresses – to create an executable.

The compiler provides an entry point that calls main in one of the object files. Calling main means that we try to execute the instructions at the address stored at the location main was linked to.

Interestingly, the linker has no concept of the types of different objects – it only knows of their addresses. So, if we replace main by a regular global variable, the compiler will happily build the object file because it does not care what type of object main is, and the linker will happily link it because it is only concerned with the address of main.

So, consider this C program:

int main=0;

This will compile to an executable that tries to call address 0, which is not an address that we have access to so we get the SIGSEGV signal (Segmentation Fault).

Now we’re very close to the smallest crashing C program. We can use the trick with implicit int to shorten it further.

main=0;

Also, global variables in C are initialized to zero implicitly, so this is equivalent:

main;

And there we have it, the shortest crashing C program!

Update:

Hacker News user femto pointed out that it is possible to compile and link an empty file. I did not post this because gcc will refuse to compile and link the program - it requires compiling and linking separately.

Also, if we shall be pedantic I should point out that by "global" variable I of course mean "static" variable.


2013 Jesper Öqvist jesper.oqvist@cs.lth.se