【问题标题】:When does memory gets allocated for a variable in c?什么时候为c中的变量分配内存?
【发布时间】:2015-04-17 07:38:54
【问题描述】:

什么时候为 c 中的变量分配内存?它是否在声明或初始化期间发生?这是否因范围或存储类而有所不同?

例如:

int i; <<<<<<<< memory gets allocated here?
i=10;  <<<<<<<< memory gets allocated here?

我认为,它是在声明过程中分配的。如果我错了,请纠正我。

【问题讨论】:

  • 简而言之:取决于。分享你的案例。
  • 对于普通变量,编译器在编译时处理它。
  • @GrijeshChauhan 不在int i:如果块范围,在块的入口处声明i,请参阅我的答案。
  • @ouah 是的,我看到了你的答案,但我不确定内存是否未在int i 分配。 编辑好的,你说得对,谢谢
  • 自动变量通常分配在前面的{符号

标签: c variables declaration


【解决方案1】:
  • 局部函数变量分配在the stack frame 上,并在您调用函数时进行初始化。
  • 传递给函数的参数要么在堆栈上,要么通过寄存器传递。这取决于您的调用约定。
  • 如果您使用malloc 和朋友,他们可以分配到the heap
  • static 变量如果具有初始化值 (static int a=1;) 则分配在 data section 中,否则它们将隐式清零并分配在 BSS section (static int a;) 中。它们在调用 main 之前被初始化。

至于你的具体例子,

int i;
i = 10;

编译器将在堆栈帧上分配i。它可能会立即设置该值。所以它会在进入那个作用域时分配和初始化它。

举个例子

#include <stdio.h>

int main()
{
  int foo;
  foo = 123;
  printf("%d\n", foo);
}

现在编译这个

gcc -O0 a.c -S

这会产生汇编文件a.s。如果您检查它,您确实会看到 foo 被复制到堆栈帧上:

movl    $123, -4(%rbp)

或者,在 Intel 语法中(将 -masm=intel 添加到 gcc):

mov     DWORD PTR [rbp-4], 123

您将在其下方看到call printfRBP register 指的是堆栈帧,所以这个变量在这种情况下只存在于堆栈帧上,因为它只在调用 printf 时使用。

【讨论】:

    【解决方案2】:

    内存可以分配:

    • 编译器在程序的数据段之一中。这些段是程序启动(或根据需要调入)时由操作系统加载的程序的一部分。 (静态变量)
    • 运行时在堆栈上。 (堆栈/自动变量)
    • 在运行时从堆中。 (通过 malloc() 或类似的东西)

    【讨论】:

      【解决方案3】:
      int bla = 12;  // bla is allocated prior to program startup
      
      int foo(void)
      {
          while (1)
          {
              /* ... code here ... */
              int plop = 42;  // plop is allocated at the entry of the while block
              static int tada = 271828; // tada is allocated prior to program startup
          }
      
          int *p = malloc(sizeof *p);  // object is allocated after malloc returns
      }
      

      【讨论】:

      • 感谢您的回答。但我想知道在声明或初始化变量期间是否分配了内存?
      • 我想打破声明并分配给 OP,我试过your code
      • @Karthick 在您的示例中 int i; i = 10; 不是初始化,而是赋值语句。在块范围内,i 对象在声明它的 { 打开时分配。
      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 2015-09-15
      • 2011-10-28
      • 2013-11-24
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2015-01-22
      相关资源
      最近更新 更多