Reputation:
According to our book, each function has an activation record in the run-time stack in C. Each of these activation records has a return address, dynamic link, and return value. Does main have these also?
Upvotes: 6
Views: 3983
Reputation: 2452
While this depends on the implementation, it is worthy looking at a C program compiled with gcc. If you run objdump -d executable
, you will see it disassembled and you can see how main()
behaves. Here's an example:
08048680 <_start>:
...
8048689: 54 push %esp
804868a: 52 push %edx
804868b: 68 a0 8b 04 08 push $0x8048ba0
8048690: 68 30 8b 04 08 push $0x8048b30
8048695: 51 push %ecx
8048696: 56 push %esi
8048697: 68 f1 88 04 08 push $0x80488f1
804869c: e8 9f ff ff ff call 8048640 <__libc_start_main@plt>
80486a1: f4 hlt
...
080488f1 <main>:
80488f1: 55 push %ebp
80488f2: 89 e5 mov %esp,%ebp
80488f4: 57 push %edi
80488f5: 56 push %esi
80488f6: 53 push %ebx
...
8048b2b: 5b pop %ebx
8048b2c: 5e pop %esi
8048b2d: 5f pop %edi
8048b2e: 5d pop %ebp
8048b2f: c3 ret
You can see that main behaves similarly to a regular function in that it returns normally. In fact, if you look at the linux base documentation, you'll see that the call to __libc_start_main
that we see from _start
actually requires main
to behave like a regular function.
Upvotes: 2
Reputation: 11791
In C/C++, main()
is written just like a function, but isn't one. For example, it isn't allowed to call main()
, it has several possible prototypes (can't do that in C!). Whatever is return
ed from it gets passed to the operating system (and the program ends).
Individual C implementations might handle main()
like a function called from "outside" for uniformity, but nobody forces them to do so (or disallow switching to some other form of doing it without telling anybody). There are traditional ways of implementing C, but nobody is forced to do it that way. It is just the simplest way on our typical architectures.
Upvotes: 0
Reputation:
If you disassemble functions you will realize that most of the time the stack doesn't even contain the return value - often times the EAX register does (intel x86). You can also look up "calling conventions" - it all pretty much depends on the compiler. C is a language, how it's interpreted into machine code is not 'its' business.
Upvotes: 2
Reputation: 372814
All of these terms are purely implementation details - C has no notion of "return addresses" or "dynamic links." It doesn't even have a notion of a "stack" at all. Most implementations of C have these objects in them, and in those implementations it is possible that they exist for main
. However, there is no requirement that this happen.
Hope this helps!
Upvotes: 6