StackOverflowException occurs when a method is called recursively, infinitely many times. Different stack frames are allocated to each recursive call -- multiple stack frames are used in this case. As we know, a stack frame is allocated to each method call. Can the stack overflow when using a single method in C# (using a single stack frame)?
can the stack be overflown with using single method
Sure:
static unsafe void Main()
{
for(int i = 0; i < 50; i++)
{
// fails on i=18 for me
long* ptr = stackalloc long[10 * 1024];
}
}
A stack overflow happens when the stack is fully consumed. There are multiple ways to do that; recursion is just one of them. stackalloc
creates a pointer to (or more recently: a span over) a block of memory at the current stack-frame, extending the current stack-frame; it will be conceptually reclaimed (although in reality, this just means changing a single number) when you return (or throw, etc) from the method that allocated it.
Another way would be to create an absurdly over-sized value-type:
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;
}