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?
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