stackalloc 关键字用于不安全的代码上下文中,以便在堆栈上分配内存块。如下:
int* block = stackalloc int[100];
下面的代码导致编译器错误。
int* block; // The following assignment statement causes compiler errors. You // can use stackalloc only when declaring and initializing a local // variable. block = stackalloc int[100];
不安全代码和指针(C# 编程指南)。
_alloca。
int 类型元素的内存块是在堆栈上分配的,而不是在堆上分配的。
不能在方法返回之前释放内存。
class Test { static unsafe void Main() { const int arraySize = 20; int* fib = stackalloc int[arraySize]; int* p = fib; // The sequence begins with 1, 1. *p++ = *p++ = 1; for (int i = 2; i < arraySize; ++i, ++p) { // Sum the previous two numbers. *p = p[-1] + p[-2]; } for (int i = 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(); } } /* Output 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 */
如果检测到缓冲区溢出,进程将尽快终止,以最大限度地减小执行恶意代码的机会。