Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is memory space allocated to a variable?

Tags:

java

Does the compiler allocate 4 bytes of memory when the variable is declared:

int a;

Or does it allocate memory when a value is assigned to it:

a = 5;

When is memory allocated? During variable declaration or initialization?

like image 971
Souhardya Mondal Avatar asked Dec 20 '22 07:12

Souhardya Mondal


2 Answers

The variable is allocated when the structure containing it is allocated.

For a local variable in a method this is (with some caveats) when the method is invoked.

For a static variable this is when the class is "initialized" (which happens some time after it's loaded and before it's first used).

For an instance variable this is when the instance is created.

like image 153
Hot Licks Avatar answered Dec 21 '22 20:12

Hot Licks


In most programming languages the compiler is allowed to choose when to allocate space for variables. The only thing you are guaranteed, is that the storage will be available if and when you need it.

A short anecdote...

The C programming language used to require that all variables used in a method be declared at the top of the method. This was because compilers used to reserve storage for all stack (local) variables in a method as soon as you entered the method. Today that requirement doesn't exist in part because compilers are a lot smarter.

Most compilers of C-like languages will defer allocation of instances until first use for optimized code. The REALLY tricky thing here is that the first use may not be where you think it is, and it may not occur at all. For example, if you have the following code:

int foo(int x) {
  int y = 5;
  if (x > 5)
    y += x;
  return y;
}

You might think the first use is when you assign 5 to y, but the compiler could optimize that code to something more like:

int foo(int x) {
  if (x > 5)
    return 5 + x;
  return 5;
}

In this code y never really exists at all.

TL;DR - The compiler actually isn't guaranteed to allocate memory on declaration or use. Trust the compiler, it is (usually) smarter than us all.

like image 25
Beanz Avatar answered Dec 21 '22 20:12

Beanz