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
*/

如果检测到缓冲区溢出,进程将尽快终止,以最大限度地减小执行恶意代码的机会。

相关文章:

  • 2022-12-23
  • 2021-05-30
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2021-04-09
  • 2021-08-18
  • 2022-01-08
  • 2022-01-27
  • 2021-10-23
  • 2021-12-22
  • 2022-12-23
相关资源
相似解决方案