Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The shortest C program, still causes segfault

For a moment I was very proud of myself to have written my probably first C bug-free program. Here is the entire source code:

int main; 

It compiles perfectly even without the int, but a warning is issued (even without -Wall) and, as a programmer who is aiming at a bug-free program, I treat them as errors.

Having happily compiled this application, I immediately rushed to launch it. To my surprise, a segmentation fault error appeared...


Now seriously. What is exactly happening?

My guess is as follows: it's the lack of main's definition. This is so obvious and yet the compiler permits it. OK, main may be defined in a different unit. But even the linker doesn't do anything about it. Any particular reason why?

like image 744
emesx Avatar asked Mar 11 '13 07:03

emesx


People also ask

What can cause a segfault in C?

In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).

How does a segmentation fault occur?

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).


1 Answers

The word main is a legal name for any variable. The typical use case is to provide a function of the name main to a compiler, which compiles it to an object file, which in turn is linked to with crt0.o that provides initialization for run-time (stack allocation etc.) and jumps to the label main.

In C object files the symbols are not associated with prototypes and the linker succeeds in linking a global variable int main; as the main program to be jumped to. This program, however, is garbage. It's most likely initialized as zeros, but soon the processor encounters either a random instruction that accesses memory outside the programs allocated data space (stack + heap), or the instruction flow reaches the limits of the reserved code space.

Both will cause a segmentation fault. And actually, if the system runs on an architecture with eXecution flags, the program segfaults at the first attempt to jump to data segment or page without execution permission.

Further reading to support the discussion in the comments: Data Execute Prevention, NX_bit

like image 161
Aki Suihkonen Avatar answered Sep 19 '22 23:09

Aki Suihkonen