System.StackOverflowException
is thrown. Finally,
stackalloc
can be used only in an unsafe context.
Normally, memory for objects is allocated from the
heap,
which is a region of free memory.
Allocating memory from the stack is the exception. Variables allocated on the stack are not
garbage-collected. Rather, they exist only while the method in which they are declared is
executing. When the method is left, the memory is freed. One advantage to using
stackalloc
is
that you don’t need to worry about the memory being moved about by the garbage collector.
Here is an example that uses
stackalloc
:
// Demonstrate stackalloc.
using System;
class UseStackAlloc {
unsafe static void Main() {
int* ptrs = stackalloc int[3];
ptrs[0] = 1;
ptrs[1] = 2;
ptrs[2] = 3;
for(int i=0; i < 3; i++)
Console.WriteLine(ptrs[i]);
}
}
The output is shown here:
1
2
3
Do'stlaringiz bilan baham: |