Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where goes the ret instruction of the main

I learned how assembly (x86) globally works in the book : "Programming from ground up". In this book, every program ends with an interruption call to exit.

However, in C compiled programs, I found out that programs end with a ret. This supposes that there is an address to be popped and that would lead to the end of the program.

So my question is : What is this address? (And what is the code there?)

like image 936
DJ_Joe Avatar asked Mar 07 '23 13:03

DJ_Joe


1 Answers

You start your program by asking the OS to pass control to the start or _start function of your program by jumping to that label in your code. In a C program the start function comes from the C library and (as others already said before) does some platform specific environment initialization. Then the start function calls your main and the control is yours. After you return from the main, it passes control back to the C library that terminates the program properly and does the platform specific system call to return control back to the OS.

So the address main pops is a label coming from the C library. If you want to check it, it should be in stdlib.h (cstdlib) and you will see it calling exit that does the cleanup.

Its function is to destroy the static objects (C++ of course) at program termination or thread termination (C++11). In the C case it just closes the streams, flushes their buffers, calls atexit functions and does the system call.

I hope this is the answer you seek.

like image 175
Corrosive Avatar answered Mar 19 '23 22:03

Corrosive