📜 ⬆️ ⬇️

The smallest crash program in C

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

int main() { return 1/0; } 

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

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

The code does not specify the data type for the variable i . The C89 specs assume that in this case integer int is implied. In C99 and some other C variants, this would be a mistake. Suppose we write C89, in which case we can even shorten the int main() to main() .
')
 i; main() { i=1/0; } 

Only 16 characters are left, except for redundant spaces, and there is no place to optimize anymore. But in fact, you can write an even shorter crash program. The fact is that in the process of compiling a program, the compiler creates one or more object modules with symbolic links to libraries and static variables and functions.

The 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 to run - and binds to it main in one of the object modules. The main call means that we are trying to execute the instructions at the address referenced by main .

Interestingly, the linker has no idea about the data types of different objects. So if we replace main with a static variable, the compiler will gladly create an object module, and the linker will then replace the symbolic reference to the address in memory.

Jesper Equist offers the following C program:

 int main=0; 

Such a program crashes because it tries to execute main as a function, while the compiler has placed it in a non-executable data segment.

Further optimizations are obvious. You can use the above trick with the abbreviation 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 crash program in C.

Source: https://habr.com/ru/post/181021/


All Articles