问题描述
我知道我们使用这个论点的目的,我什至知道如何处理这个论点.
I know for what we use this argument, and I even know how to work with the argument.
只有一件事我仍然不明白.程序如何为来自输入的字符串分配内存.**argv 在程序开始时没有分配内存,不是吗?我期待段错误,但它没有发生.
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?
推荐答案
C/C++ 运行时处理命令行参数并创建一个内存区域来放置参数.然后它调用您的 main()
为您提供参数数量的计数以及指向存储参数区域的指针.
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.
因此,C/C++ 运行时拥有分配的内存区域,一旦 main()
返回或其他 C/C++ 函数被调用,则由 C/C++ 运行时释放该区域用于停止程序如exit()
.
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()
.
这个过程起源于 Unix 下 C 的使用,并为 C++ 保留,作为提供 C++ 委员会试图保持的向后兼容性程度的一部分.
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.
通常在您的程序加载时,加载器启动的入口点不是您的 main()
函数,而是在 C/C++ 运行时中定义的入口点.C/C++ 运行时会进行各种初始化,以设置 C/C++ 标准所说的环境,即 C/C++ 运行时在初始化后调用 main()
函数时将存在的环境完成.
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.
此初始化过程中的一个步骤是解析提供的命令行参数,然后将这些参数作为函数参数提供给 main()
函数.
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.
这篇关于内存分配和 **argv 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!