Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does memory gets allocated for a variable in c?

When does memory gets allocated for a variable in c? Does it happen during declaration or initialization? Does this differ based on the scope or storage class?

Eg:

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

I think, it gets allocated during declaration itself.Correct me if I am wrong.

like image 550
Karthick Avatar asked Dec 05 '22 22:12

Karthick


2 Answers

  • Local function variables are allocated on the stack frame and initialized when you call the function.
  • Arguments passed to functions are either on the stack or passed through registers. This depends on your calling convention.
  • They can be allocated on the heap, if you use malloc and friends.
  • The static variables are allocated in the data section if they have initialization values (static int a=1;), otherwise they will implicitly be zeroed out and allocated in the BSS section (static int a;). They are initialized before calling main.

As for your specific example,

int i;
i = 10;

the compiler will allocate i on the stack frame. It will probably set the value right away. So it will allocate and initialize it when entering that scope.

Take for instance

#include <stdio.h>

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

Now compile this with

gcc -O0 a.c -S

This produces the assembly file a.s. If you inspect it, you will indeed see that foo is copied right on the stack frame:

movl    $123, -4(%rbp)

or, in Intel syntax (add -masm=intel to gcc):

mov     DWORD PTR [rbp-4], 123

Right below that you will see a call printf. The RBP register refers to the stack frame, so this variable in this case only ever exists on the stack frame, because it's only used in the call to printf.

like image 148
csl Avatar answered Dec 30 '22 09:12

csl


Memory can be allocated:

  • In one of the program's data segments by the compiler. These segments are part of the program loaded by the OS when the program starts (or paged in as needed). (Static variables)
  • On the stack at runtime. (Stack/auto variables)
  • From the heap at runtime. (Via malloc() or something similar)
like image 25
Craig S. Anderson Avatar answered Dec 30 '22 09:12

Craig S. Anderson