Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does variable declaration mean memory allocation?

Tags:

c

Will it be precise to say that in

void f() {
    int x;
    ...
}

"int x;" means allocating sizeof(int) bytes on the stack?

Are there any specifications for that?

like image 751
Evgeny Avatar asked Sep 17 '13 07:09

Evgeny


People also ask

Does variable declaration allocate memory?

It depends on a lot of factor. The compiler can optimize and remove it from the stack, keeping the value in register. etc. If you compile in debug it certainly does allocate some space in the stack but you never know.

How does variable declaration affect memory allocation?

The amount of memory to be allocated or reserved would depend on the data type of the variable being declared. For example, if a variable is declared to be of integer type, then 32 bits of memory storage will be reserved for that variable.

Is memory allocated during declaration or initialization?

Memory is allocated when a variable is declared, not when it's initialized.

Is memory allocated for variable declaration in C?

Program to Illustrate the Declaration of Variables in C And then use that variable name to access the data. While declaring a variable, memory space is not allocated to it. It happens only on initializing the variable.


2 Answers

Nothing in the standard mandates that there is a stack. And nothing in the standard mandates that a local variable needs memory allocated for it. The variable could be placed in a register, or even removed altogether as an optimization.

like image 180
David Heffernan Avatar answered Oct 06 '22 16:10

David Heffernan


There are no specification about that and your assumption is often (but not always) false. Consider some code like

void f() {
   int x;
   for (x=0; x<1000; x++) 
     { // do something with x 
     }
   // x is no more used here
}

First, an optimizing compiler would put x inside some register of the machine and not consume any stack location (unless e.g. you do something with the address &x like storing it in a global).

Also the compiler could unroll that loop, and remove x from the generated code. For example, many compilers would replace

for (x=0; x<5; x++) g(x);

with the equivalent of

g(0); g(1); g(2); g(3); g(4);

and perhaps replace

for (x=0; x<10000; x++) t[x]=x;

with something like

for (α = 0;  α < 10000;  α += 4) 
  { t[α] =  α; t[α+1] =  α+1; t[α+2] =  α+2; t[α+3] =  α+3; };

where α is a fresh variable (or perhaps x itself).

Also, there might be no stack. For C it is uncommon, but some other languages did not have any stack (see e.g. old A.Appel's book compiling with continuations).

BTW, if using GCC you could inspect its intermediate (Gimple) representations with e.g. the MELT probe (or using gcc -fdump-tree-all which produces hundreds of dump files!).

like image 31
Basile Starynkevitch Avatar answered Oct 06 '22 18:10

Basile Starynkevitch