The smallest failed C program

    The Swedish student Jesper Öqvist received his homework at the university: write the smallest C program , which crashes with an error (segfault, SIGFPE). Usually students in such situations use division by zero.

    int main()
    {
        return 1/0;
    }

    You can still remove a couple of bytes from this code if you use variable assignment instead of an instruction.

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

    The code does not specify the data type for the variable i. The C89 specs suggest that the whole is implied in this case int. In C99 and some other variants of C, this would be a mistake. Suppose we write in C89, in which case we can even shorten int main()to main().

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

    There are only 16 characters left, except for excessive spaces, and there is nowhere to optimize more. But in fact, you can write an even shorter failed program. The fact is that during the compilation of a program, the compiler creates one or more object modules with symbolic links to libraries and static variables and functions.

    A symbolic link contains only the name of the variable. Subsequently, the object module is processed by the linker, which replaces symbolic links to addresses to make a ready-made executable module.

    The compiler sets the entry point — the address in RAM from which the program starts — and binds to it mainin one of the object modules. Callmainmeans that we are trying to follow the instructions at the address to which it refers main.

    Interestingly, the linker has no idea about the data types of different objects. So if we replace it mainwith a static variable, the compiler will be happy to create an object module, and the linker will then replace the symbolic link to the address in memory.

    Jesper Equist offers such a program in C:

    int main=0;

    Such a program crashes because it tries to execute mainas a function, while the compiler placed it in an unexecutable segment with data.

    Further optimizations are obvious. You can use the aforementioned shortcut trick int.

    main=0;

    Anyway, static variables in C are initialized to zero by default, so you can make the code even more concise.

    main;

    Here it is, the smallest failed program in C.

    Also popular now: