A single statement without main function in c

A sample.c file is written with only one single statement.

main;

Segmentation fault occurred when executed that file.

Any statement other than

main;

is written, for example

unix;

then it won't compile.

why is this behaviour !

read some book on C :wink: C program must have main() function to run. With this statement

main;

you define a symbol with name "main". Both link and compiler require this symbol and you defined it. That's why compilation and linkage works. But when you start the compiled program it tries to call the function with the name "main". It finds the symbol main in the symbol table and makes jump to the symbol definition. But because you didn't define the symbol as function it is unpredictable what is now held in the memory under the symbol main. Hopefully nulls. As result you receive core dumped, because kernel can't execute nulls or finds no instruction to execute.

When you write "unix" instead of "main", you didn't define "main" symbol and the program can't be compiled without main.

1 Like
int main()
{
    return 0;
}

This is the most "minimal" legal C program. It is not obvious but main is in fact a function, not the real beginning of the compiled code. When you link a C program the linker adds (something like) two functions: _start() and _end() The actual names are implementation dependent. _start() sets up a lot of memory objects and files like stdout and stdin _end() cleans up after _start()

If main is not fully declared you get undefined behavior. Undefined behavior is just that - the program may dump core, panic the kernel, format your disk, or send family pictures to the Mars explorer.

1 Like