在哪个内存段命令行参数存储?

时间:2013-09-08 06:25:09

标签: c linux gcc

命令行参数argcarv[],与C中的main函数一起使用,它们存储在内存中?

我正在寻找这个问题的存储区应该是堆,数据段,堆栈或其他。

2 个答案:

答案 0 :(得分:3)

语言没有指定。

类Unix系统将它们放在堆栈上(或者在一些更深奥的系统中,“堆栈”,因为它们有多个)。

答案 1 :(得分:1)

正如torek在他的answer中所说,C语言没有定义必须存储命令行参数的位置,并且知道没有太多实际用途。但是,信息通常存储在堆栈中。

此代码使用main()的公共扩展来获取环境,然后打印参数和环境的地址。

#include <stdio.h>
#include <inttypes.h>

int main(int argc, char **argv, char **envp)
{
    printf("&argc = 0x%.8" PRIXPTR "\n", (uintptr_t)&argc);
    printf("&argv = 0x%.8" PRIXPTR "\n", (uintptr_t)&argv);
    printf("&envp = 0x%.8" PRIXPTR "\n", (uintptr_t)&envp);
    while (*argv != 0)
        printf("*argv = 0x%.8" PRIXPTR "\n", (uintptr_t)*argv++);
    while (*envp != 0)
        printf("*envp = 0x%.8" PRIXPTR "\n", (uintptr_t)*envp++);
    return 0;
}

在我的Mac上运行时,显示:

&argc = 0x7FFF5494B52C
&argv = 0x7FFF5494B520
&envp = 0x7FFF5494B518
*argv = 0x7FFF5494B748
*envp = 0x7FFF5494B74E
*envp = 0x7FFF5494B839
*envp = 0x7FFF5494B862
*envp = 0x7FFF5494B86D
*envp = 0x7FFF5494B889
*envp = 0x7FFF5494B8C1
*envp = 0x7FFF5494B8F4
*envp = 0x7FFF5494B905
*envp = 0x7FFF5494B915
*envp = 0x7FFF5494B920
*envp = 0x7FFF5494B92E
*envp = 0x7FFF5494B93B
*envp = 0x7FFF5494B974
*envp = 0x7FFF5494B998
*envp = 0x7FFF5494B9CD
*envp = 0x7FFF5494B9F2
*envp = 0x7FFF5494BA0B
*envp = 0x7FFF5494BA2A
*envp = 0x7FFF5494BA46
*envp = 0x7FFF5494BA7B
*envp = 0x7FFF5494BB2E
*envp = 0x7FFF5494BB3C
*envp = 0x7FFF5494BB76
*envp = 0x7FFF5494BB87
*envp = 0x7FFF5494BB9D
*envp = 0x7FFF5494BBC8
*envp = 0x7FFF5494BBEA
*envp = 0x7FFF5494BC2B
*envp = 0x7FFF5494BC35
*envp = 0x7FFF5494BC51
*envp = 0x7FFF5494BC5F
*envp = 0x7FFF5494BC75
*envp = 0x7FFF5494BC82
*envp = 0x7FFF5494BD55
*envp = 0x7FFF5494BD7E
*envp = 0x7FFF5494BD96
*envp = 0x7FFF5494BDA3
*envp = 0x7FFF5494BDAE
*envp = 0x7FFF5494BDBF
*envp = 0x7FFF5494BDCA
*envp = 0x7FFF5494BDE8
*envp = 0x7FFF5494BE01
*envp = 0x7FFF5494BE09
*envp = 0x7FFF5494BE1E
*envp = 0x7FFF5494BE38
*envp = 0x7FFF5494BE52
*envp = 0x7FFF5494BE71
*envp = 0x7FFF5494BE7D
*envp = 0x7FFF5494BEF5
*envp = 0x7FFF5494BF16
*envp = 0x7FFF5494BF27
*envp = 0x7FFF5494BF32
*envp = 0x7FFF5494BF66
*envp = 0x7FFF5494BF8D

这是非常令人兴奋的,但表明所有地址都在同一个通用区域,即C堆栈。 (在Mac OS X 10.8.4上测试 - 64位程序,在没有任何命令行参数和较大环境的情况下调用。)