Memory allocation and **argv argument [closed]

眉间皱痕 提交于 2019-12-05 21:24:29

问题


I know for what we use this argument, and I even know how to work with the argument.

There is only one things I still do not understand. How a program allocate memory for strings which came from the input. **argv has no allocated memory at the start of the program, isn't it? I was expecting segfault, but it didn't happen.

Does anybody know how this memory allocation work?


回答1:


The C/C++ runtime processes the command line arguments and creates an area of memory where the arguments are put. It then calls your main() providing you a count of the number of arguments along with a pointer to the area where the arguments are stored.

So the C/C++ runtime owns the memory area allocated and it is up to the C/C++ runtime to deallocate the area once your main() returns or if some other C/C++ function is used to stop the program such as exit().

This procedure originated with the use of C under Unix and was kept for C++ as a part of providing the degree of backwards compatibility the C++ committee has tried to maintain.

Normally when your program loads, the entry point that is started by the loader is not your main() function but rather an entry point defined in the C/C++ runtime. The C/C++ runtime does various kinds of initialization to setup the environment that the C/C++ standards say will exist at the point when the main() function is called by the C/C++ runtime once the initialization is completed.

One of the steps during this initialization is the parsing of command line arguments provided which are then provided to the main() function as its function arguments.



来源:https://stackoverflow.com/questions/25850285/memory-allocation-and-argv-argument

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