5

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?

9
  • 6
    Actually, in c++ you can with alloca. Commented May 17, 2018 at 6:49
  • 2
    You might walso want to look into how GCC implenents Variable Length Arrays. Commented May 17, 2018 at 6:50
  • 2
    As an FYI, C99 allows variable length arrays (i.e. size determined at runtime), there's also alloca in C.
    – Hasturkun
    Commented May 17, 2018 at 6:50
  • 3
    The "dynamic" stac can be allocated at the end of the "fixed" stack of the method (so at the end of the maximum size the fixed stack can have in the method... can be calculated)... So no problem. There is an instruction in the IL language (the assembly language of .NET), maxstack, that declares the maximum size of the fixed stack used by the method.
    – xanatos
    Commented May 17, 2018 at 7:03
  • 2
    @BercoviciAdrian the "stack frame" is merely the distance between the addresses held by the stack pointer and the frame pointer. If you decrease the stack pointer, your frame gets bigger. Commented May 17, 2018 at 7:08

1 Answer 1

7

"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.

1
  • 3
    What are the specific risks of stackalloc in C#? Commented May 18, 2018 at 8:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.