Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stackalloc accepts a variable length?

Any idea why the 'stackalloc' keyword accepts a variable length?

If this instruction returns a pointer to a buffer allocated in the stack's frame, how the compiler manage that? It recompiles the function at runtime every time it's called to organize the stack frame?

Thanks.

like image 733
andresantacruz Avatar asked May 14 '16 20:05

andresantacruz


1 Answers

Any idea why the stackalloc keyword accepts a variable length?

Because it is useful and desirable to be able to do so, and hence the language designers chose to allow it.

If this instruction returns a pointer to a buffer allocated in the stack's frame, how the compiler manage that? It recompiles the function at runtime every time it's called to organize the stack frame?

The localalloc instruction allocates the memory after the stack-current frame, and the assignment just stores the address back into your local. Hence: it is not necessary to recalculate anything, except to update the end of the stack-frame so that it doesn't get overwritten if we call into another method.

(note: as usual when discussing the stack, this is actually an implementation detail; the JIT is in theory at liberty to do allocate it from anywhere it wants as long as it respects the semantics)

like image 81
Marc Gravell Avatar answered Nov 18 '22 20:11

Marc Gravell