From this question, I’ve seen a funny code which compile (although with warnings) and produce a segmentation fault (gcc 4.4.4; clang 2.8):
main;
If we expand it, here is the result:
int main = 0;
So what is the linker’s behavior here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The linker’s behavior is that it defines a symbol called
mainin either the program’s data or BSS segment. It is 4 bytes long and initialized to 0. Ordinarily, it creates a symbol in the program’s code segment (typically called.text) with the executable code for themainfunction.The C runtime starts up at a fixed entry point (typically called
_start), initializes a bunch of stuff (e.g. sets up the program’s arguments), and calls themainfunction. Whenmainis executable code, this is all fine and dandy, but if it’s instead 4 zero bytes, the program will transfer control to those zero bytes and try to execute them.Typically, the data and BSS segments are marked as non-executable, so when you try to execute code there, the processor will raise an exception, which the OS will interpret and then terminate your program with a signal. If somehow the segment it’s in is executable, then it will try to execute the machine instructions defined by
00 00 00 00. In x86 and x86-64, that’s an illegal instruction, so you’d also get aSIGILLsignal in POSIX OSes.