C#不安全代码和stackalloc

时间:2023-03-09 03:21:29
C#不安全代码和stackalloc

stackalloc 关键字用于不安全的代码上下文中,以便在堆栈上分配内存块。如下:

int* block = stackalloc int[];

注意:关键字仅在局部变量的初始值中有效。 下面的代码导致编译器错误。

int* block;
// The following assignment statement causes compiler errors. You
// can use stackalloc only when declaring and initializing a local
// variable.
block = stackalloc int[];

由于涉及指针类型,因此 stackalloc 要求不安全上下文。 有关更多信息,请参见 不安全代码和指针(C# 编程指南)

stackalloc 类似于 C 运行库中的 _alloca

以下代码示例计算并演示 Fibonacci 序列中的前 20 个数字。 每个数字是先前两个数字的和。 在代码中,大小足够容纳 20 个 int 类型元素的内存块是在堆栈上分配的,而不是在堆上分配的。

该块的地址存储在 fib 指针中。 此内存不受垃圾回收的制约,因此不必将其钉住(通过使用 fixed)。 内存块的生存期受限于定义它的方法的生存期。 不能在方法返回之前释放内存。

class Test
{
static unsafe void Main()
{
const int arraySize = ;
int* fib = stackalloc int[arraySize];
int* p = fib;
// The sequence begins with 1, 1.
*p++ = *p++ = ;
for (int i = ; i < arraySize; ++i, ++p)
{
// Sum the previous two numbers.
*p = p[-] + p[-];
}
for (int i = ; 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
*/

不安全代码的安全性低于安全替代代码。 但是,通过使用 stackalloc 可以自动启用公共语言运行时 (CLR) 中的缓冲区溢出检测功能。 如果检测到缓冲区溢出,进程将尽快终止,以最大限度地减小执行恶意代码的机会。

相关文章