Without using recursion how can a stack overflow exception be thrown?

前端 未结 10 2070
自闭症患者
自闭症患者 2021-01-18 04:19

Without using recursion how can a stack overflow exception be thrown?

10条回答
  •  自闭症患者
    2021-01-18 05:10

    Short answer: if you have an object which calls an internal object, you increase the stack trace by 1. So, if you have 1000s of objects nested inside one another, each calling its internal object, eventually you'll get a stack overflow.

    Here's a demonstration of how to generate primes using nested iterators:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Program p = new Program();
    
                IEnumerator primes = p.AllPrimes().GetEnumerator();
                int numberOfPrimes = 1000;
                for (int i = 0; i <= numberOfPrimes; i++)
                {
                    primes.MoveNext();
                    if (i % 1000 == 0)
                    {
                        Console.WriteLine(primes.Current);
                    }
                }
                Console.ReadKey(true);
            }
    
            IEnumerable FilterDivisors(IEnumerator seq, int num)
            {
                while (true)
                {
                    int current = seq.Current;
                    if (current % num != 0)
                    {
                        yield return current;
                    }
                    seq.MoveNext();
                }
            }
    
            IEnumerable AllIntegers()
            {
                int i = 2;
                while (true)
                {
                    yield return i++;
                }
            }
    
            IEnumerable AllPrimes()
            {
                IEnumerator nums = AllIntegers().GetEnumerator();
                while (true)
                {
                    nums.MoveNext();
                    int prime = nums.Current;
                    yield return prime;
    
                    // nested iterator makes a big boom     
                    nums = FilterDivisors(nums, prime).GetEnumerator();
                }
            }
        }
    }
    

    There's no recursion, but the program will throw a stack overflow exception after around 150,000 primes.

提交回复
热议问题