【问题标题】:Stackoverflow Exception and the recursive methodsStackoverflow 异常和递归方法
【发布时间】:2014-11-01 11:35:23
【问题描述】:

为什么这些顶部的应用程序不抛出堆栈溢出异常?递归方法是怎么回事?我知道底部示例创建了一个深层调用堆栈,因此它会引发错误。但是第一个例子是我们使用内存中的相同空间还是垃圾收集器帮助我们。

class ProgramErrorFree
{
    static void Main()
    {
       while(true)
        {
            Console.WriteLine(Guid.NewGuid());
        }
    }
}

class ProgramStackOverFlow
{
    static void Recursive(int value)
    {
        // Write call number and call this method again.
        // ... The stack will eventually overflow.
        Console.WriteLine(value);
        Recursive(++value);
    }

    static void Main()
    {
        // Begin the infinite recursion.
        Recursive(0);
    }
}

【问题讨论】:

    标签: c# memory-management garbage-collection


    【解决方案1】:

    为什么这些顶部的应用程序不抛出堆栈溢出异常?

    你为什么期望它?来自MSDN: StackOverflowException Class

    执行堆栈溢出时抛出的异常因为它包含太多的嵌套方法调用

    你的堆栈永远不会超过两帧:

    • ProgramErrorFree.Main()
      • Guid.NewGuid()
      • Console.WriteLine()

    而你的第二个程序堆栈帧不断堆积:

    • ProgramStackOverFlow.Main()
      • ProgramStackOverFlow.Recursive()
        • ProgramStackOverFlow.Recursive()
          • ProgramStackOverFlow.Recursive()
            • ProgramStackOverFlow.Recursive()
              • ProgramStackOverFlow.Recursive()

    以此类推,直到堆栈空间用完为止。

    我认为您希望Guid.NewGuid() 快速连续“溢出”堆栈,但这不是它的工作原理。请参阅 Eric Lippert 的博客 The Stack Is An Implementation Detail, Part One 并进一步了解堆栈是什么以及它的用途。

    另请参阅Running out of ValueType stack space,了解如何在没有递归的情况下耗尽堆栈空间。

    【讨论】:

    • 真正的好答案。感谢您链接 Eric Lippert 博客文章。
    猜你喜欢
    • 2013-11-21
    • 2018-01-03
    • 2017-09-13
    • 2013-11-15
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多