Why does writing main; in C give a segfault

The following is my demo.c file:

main;

On compiling this gcc gives a warning:

demo.c:1:1: warning: data definition has no type or storage class [enabled by default]

Running ./a.out gives a Segmentation Fault:

Segmentation fault (core dumped)

Is it because, (1) main is not defined anywhere and we are trying to execute it and (2) we are using an imperative statement outside any function, so it can't execute.

In either case, I still don't understand why it should throw a segfault.

Update: It might look similar to Is 'int main;' a valid C/C++ program?, but this is different, as not using any identifier, compiles the code.


Your code is formally illegal in standard C (it is generally "non-compilable"). The diagnostic message you received was intended to tell you exactly that.

However, your compiler apparently accepted it and interpreted it is some implementation-specific way. Apparently it interpreted that main as a definition for an int variable with external linkage (legacy K&R C-specific behavior). It created an object file that exports a single external symbol main (likely mangled in some implementation-specific way). Later linker registered that main as your program's entry point.

When you attempt to run your executable, loader passes control to the location of that main variable, mistakenly believing that this is program's entry point. The program crashes, since there's no valid executable code at that location. Or, more likely, it is data execution prevention that causes the program to crash.

链接地址: http://www.djcxy.com/p/79934.html

上一篇: 在C中的main()函数之前打印“Hello world”

下一篇: 为什么写作主要; 在C给出段错误