How to create local variables inside the main function?

元气小坏坏 提交于 2019-12-11 14:57:47

问题


I know how to pass parameters to a user-defined function and how to create local variables inside such function. But what I want is to create local variables for the main function.

So the main function is the first thing that executes when the program starts, but what is the initial value of esp when main starts executing? i.e what is on top of the stack when main starts executing, is it the command line arguments?

If I want to create local variables inside main, should I save the value of esp into ebp and then increment esp by how much data I need just like I do inside of a user-defined function?


回答1:


So the main function is the first thing that executes when the program starts, but what is the initial value of esp when main starts executing? i.e what is on top of the stack when main starts executing, is it the command line arguments?

main is called as a normal function, so (with cdecl calling convention), the topmost things are, from the top to the bottom, (optionally) the environment pointer, then the pointer to the argument string pointer array, then argc, then the return address of main.

If I want to create local variables inside main, should I save the value of esp into ebp and then increment esp by how much data I need just like I do inside of a user-defined function?

main is a user function. It is called from crt0.o (name may differ depending on the operating system) from code roughly like this:

void
_start(void)
{
    /* initialisation skipped */
    int rv = main(newargc, newargv, environ);
    do_global_dtors();
    exit(rv);
    /* NOTREACHED */
}

So, tl;dr: yes.

(Note that even _start has a valid stack pointer, but usually no return address, so it must eventually call the exit syscall.)



来源:https://stackoverflow.com/questions/27630193/how-to-create-local-variables-inside-the-main-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!