The stackalloc keyword is used in an unsafe code context to allocate memory blocks on the stack. as follows:
int stackalloc int [+];
Note: The keyword is only valid in the initial value of the local variable. The following code causes a compiler error.
int * block; // The following assignment statement causes compiler errors. You // can use stackalloc if Declaring and initializing a local // Variable. block = stackalloc int [100 ];
Because of the pointer type involved, stackalloc requires an unsafe context. For more information, see Unsafe Code and Pointers (C # Programming Guide).
stackalloc is similar to _alloca in the C Runtime library.
int are allocated on the stack, not the Hea P. " > in code, a block of memory that is large enough to hold 20 int type elements is allocated on the stack, not on the heap. The address of the block is stored in the fib pointer. This memory is not subject to garbage collection, so it is not necessary to pin it (by using fixed). The lifetime of a memory block is limited by the lifetime of the method that defines it. you cannot free memory before the method returns.
classtest{Static unsafe voidMain () {Const intArraySize = -; int* Fib =stackalloc int[ArraySize]; int) S =fib; //the sequence begins with 1, 1.*p++ = *p++ =1; for(inti =2; i < arraySize; ++i, + +p) {//Sum the previous and the numbers.*p = p[-1] + p[-2]; } for(inti =0; i < arraySize; ++i) {Console.WriteLine (fib[i]); } //Keep the console window open in debug mode.System.Console.WriteLine ("Press any key to exit."); System.Console.ReadKey (); }}/*Output11235813213455891442333776109871597258441816765*/
Unsafe code is less secure than the security override code. However, the buffer overflow detection feature in the Common language runtime (CLR) can be automatically enabled by using Stackalloc. If a buffer overflow is detected, the process terminates as soon as possible to minimize the chance of executing malicious code.
C # unsafe code and STACKALLOC