1

I want to know whether memory is allocated during the local variable declaration process.

Suppose I write this code inside function, int a =10; memory is allocated and the value 10 is stored in that.

What about int a; ? This declaration statement will it allocate 4 bytes of memory?

Thanks.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vishnu Y
  • 2,211
  • 4
  • 25
  • 38
  • 1
    I imagine so, since at that point `a` has a valid value of `0`. – David Jul 07 '14 at 12:03
  • Yep declaring a variable allocates space for it till it goes out of scope and is garbage collected. Structs like your example will have a default value, where as reference types will be declared as null. – Mark Broadhurst Jul 07 '14 at 12:05
  • possible duplicate of [Memory Allocation for Variable Declared in Class](http://stackoverflow.com/questions/7343564/memory-allocation-for-variable-declared-in-class) – huMpty duMpty Jul 07 '14 at 12:05

2 Answers2

2

When you call a method, space for each local variable is allocated on the stack.

So if you declare an int variable in a method, it's stack frame will take up an extra 4 bytes of memory.

No additional memory is used anywhere else, and it is cleaned up when the method returns.

Something important to understand here is that MSIL does not support declaring a property just anywhere in a method. Whenever you declare a variable in C#, the declaration is moved to the method header in the compiled bytecode. Every variable is allocated when the method is called.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
2

Local variables are usually stored on stack, so indeed bytes are allocated for int:

int a;

Because it simply uses default value (0), so it is the same as:

int a = 0;

int is a value type, so on stack is stored its value. If you would create local variable with reference type:

SomeClass a;

Then on stack it would be allocated only reference (with value null, as it is default value for reference types). For more information you can refer this question

Community
  • 1
  • 1
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • So you are telling like by default it takes 0 as its value. Suppose I write int a; int b=a; we will get an error like "use of unassigned local variable a". In this case why its not taking the default value 0? – Vishnu Y Jul 07 '14 at 12:34
  • `a` must have some value from **runtime** perspective (default 0), but **compiler** treats this as an error if you are using value without implicitly assigned value. – Konrad Kokosa Jul 07 '14 at 12:39
  • And one should mention that the compiler usually gets rid of unused local variables... so if you just write int a; and never read its value, it will just be erased and not even cost you space on the stack – Falco Jul 07 '14 at 12:49