0

In c# When does the memory allocation in Stack/Heap occurs. Is it during the runtime or compile time. From my study I understand that all memory allocations happens during run time for both value type and reference type. Is this correct?

Ujjal Das
  • 77
  • 1
  • 7
  • 1
    Yes, memory allocation can not happen at compile time. Only when the program is run are all the objects (`struct` or `class`) required by that program loaded into memory. – EvilTak Jul 09 '16 at 08:24
  • 1
    It is correct ...... – zerkms Jul 09 '16 at 08:24
  • 1
    One could argue that allocation on the stack occurs at compile time. Then again, the instruction that actually changes the stack pointer has to be executed at run-time. This is kind of a silly question. Perhaps you should read up on [what the stack and the heap are](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap). – Cody Gray - on strike Jul 09 '16 at 08:35
  • The C# compiler generates code for a *virtual machine*, one that's programmed in MSIL and is stack-based. As such, the compiler certainly determines what stack allocations are made. However, the just-in-time compiler does its best to use as little stack as possible. It knows that a real processor uses a mixed model. It has one or two handful of storage locations in registers, the fastest memory you can get by a factor of 3 and *very* important to use it as efficiently as possible. So it isn't straight-forward. – Hans Passant Jul 09 '16 at 10:14

2 Answers2

2

How would it happen during compile-time ? The program is not yet running and there is no need to allocate memory before the program run. It is common sense that this should happen at run-time (When actually executing the generated IL).

Memory management it also optimized that it may not happen when you just create the variable, but when you first use it.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
0

I think you might be confusing the actual allocation, which can only happen at runtime when the program is actually running, with the allocation calculation/determination. For example, consider the following method:

void Foo() 
{
    int i = 42;
    Console.WriteLine(i); 
}

The compiler will now statically (compile-time) that i will require 4 bytes of space on the stack. However, it will not be until the program actually runs that the actual allocation takes place.

Moreover, the above method won't even be compiled into machine code (a prerequisite for any operation such as allocation) until the CLR loads the code and passes it to the JIT (Just in Time compiler). Of course, even if it did, it's not until the actual process is created that the OS even allocates a memory address space for it to use...

Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198