在c#中使用single方法会不会出现Stackoverflow异常?
Will the Stackoverflow exception occur by using single method in c#?
当递归调用方法时(无限次)发生Whosebug异常(每次递归调用分配不同的栈帧,在这种情况下使用多个栈帧)。众所周知,每个方法分配一个栈帧call.can 使用单一方法(使用单个堆栈帧)时堆栈会溢出。
can the stack be overflown with using single method
当然可以:
static unsafe void Main()
{
for(int i = 0; i < 50; i++)
{
// fails on i=18 for me
long* ptr = stackalloc long[10 * 1024];
}
}
当堆栈被完全消耗时发生堆栈溢出。有多种方法可以做到这一点;递归只是其中之一。 stackalloc
在当前堆栈帧处创建一个指向(或最近:跨越)内存块的指针,扩展当前堆栈帧;当您从分配它的方法 return(或抛出等)时,它将在概念上被回收(尽管实际上,这仅意味着更改一个数字)。
另一种方法是创建一个荒谬超大值类型:
static class P
{
static void Main() => Foo();
static void Foo() => Bar(default);
static void Bar(FatStruct2097152 a) => Console.WriteLine(a);
}
struct FatStruct64 {
private long a, b, c, d, e, f, g, h;
}
struct FatStruct512 {
private FatStruct64 a, b, c, d, e, f, g, h;
}
struct FatStruct4096 {
private FatStruct512 a, b, c, d, e, f, g, h;
}
struct FatStruct32768 {
private FatStruct4096 a, b, c, d, e, f, g, h;
}
struct FatStruct262144 {
private FatStruct32768 a, b, c, d, e, f, g, h;
}
struct FatStruct2097152 {
private FatStruct262144 a, b, c, d, e, f, g, h;
}
当递归调用方法时(无限次)发生Whosebug异常(每次递归调用分配不同的栈帧,在这种情况下使用多个栈帧)。众所周知,每个方法分配一个栈帧call.can 使用单一方法(使用单个堆栈帧)时堆栈会溢出。
can the stack be overflown with using single method
当然可以:
static unsafe void Main()
{
for(int i = 0; i < 50; i++)
{
// fails on i=18 for me
long* ptr = stackalloc long[10 * 1024];
}
}
当堆栈被完全消耗时发生堆栈溢出。有多种方法可以做到这一点;递归只是其中之一。 stackalloc
在当前堆栈帧处创建一个指向(或最近:跨越)内存块的指针,扩展当前堆栈帧;当您从分配它的方法 return(或抛出等)时,它将在概念上被回收(尽管实际上,这仅意味着更改一个数字)。
另一种方法是创建一个荒谬超大值类型:
static class P
{
static void Main() => Foo();
static void Foo() => Bar(default);
static void Bar(FatStruct2097152 a) => Console.WriteLine(a);
}
struct FatStruct64 {
private long a, b, c, d, e, f, g, h;
}
struct FatStruct512 {
private FatStruct64 a, b, c, d, e, f, g, h;
}
struct FatStruct4096 {
private FatStruct512 a, b, c, d, e, f, g, h;
}
struct FatStruct32768 {
private FatStruct4096 a, b, c, d, e, f, g, h;
}
struct FatStruct262144 {
private FatStruct32768 a, b, c, d, e, f, g, h;
}
struct FatStruct2097152 {
private FatStruct262144 a, b, c, d, e, f, g, h;
}