stackalloc参考
C# 程序员参考
stackalloc(C# 参考)
在堆栈上分配内存块。
type * ptr = stackalloc type [ expr ];
参数
- Type
-
非托管类型。
- ptr
-
指针名。
- expr
-
整型表达式。
安全性不安全代码是天生比非不安全替代代码安全性更低的代码。但是,通过使用 stackalloc 可以自动启用公共语言运行库 (CLR) 中的缓冲区溢出检测功能。如果检测到缓冲区溢出,进程将尽快终止,以最大限度地减小执行恶意代码的机会。
示例// cs_keyword_stackalloc.cs
// compile with: /unsafe
using System;
class Test
{
static unsafe void Main()
{
int* fib = stackalloc int[100];
int* p = fib;
*p++ = *p++ = 1;
for (int i = 2; i < 100; ++i, ++p)
{
*p = p[-1] + p[-2];
}
for (int i = 0; i < 10; ++i)
{
Console.WriteLine(fib[i]);
}
}
}
输出
1 1 2 3 5 8 13 21 34 55
浙公网安备 33010602011771号