How does stackalloc work?

2.2k views Asked by At

Hello i am trying to figure out how does stackalloc work.So coming from C/C++ from my knowledge (limited) you can not allocate memory on the stack dynamically like in here:

C/C++ example:

   void Allocate(int length){
     int vector[length];  //wont work
   }

Then C# comes into play and you can do it with stackalloc:

     void Allocate(int length){
      int []vector=stackalloc int [length];
     }

Isn't the whole point of allocating on the stack to know at compile-time or precompile-time (macros etc) what size will the array have?How does C# manage this "magic"? How will the stack-frame be created?

1

There are 1 answers

1
einpoklum On BEST ANSWER

"Allocating on the stack" basically means moving the head of the stack further away from the base of the current function's stack frame. Usually it's by a fixed amount - the size of some local variables - but there's nothing preventing your program from moving the stack head by a variable amount, determined by one of the arguments.

The main reason this is avoided is that it makes stack overflows much more likely, and is easily abused by careless programmers. Thus the C++ standard committee decided not to adopt variable-length arrays like in C99. alloca() is a platform-specific non-standard function, which is not even part of the POSIX standard.

Edit: As @PauloMorgado points out, there's an additional consideration in C#: Allocations on the stack are not subject to garbage collection, as opposed to allocations on the heap, which may motivate using stackalloc() in C# despite the risks.