Simplest ways to cause stack overflow in C#, C++ and Java

I'm watching a C# tutorial and came across StackOverflowException.

the narrator gave a neat example of such an exception using the code snippet below,

public class Employee
{
    private string _name;

    public string Name
    {
       get{ return Name; }
    }
}

I'm looking for some example of this type of simple code in C++ and Java and more specially in javascript that can cause Stack Overflow.


In Java:

public class Test {
    public static void main(String[] args) {
        main(args);
    }
}

In general, any recursive function that does not terminate or have too many iterations will cause this problem.


This Explaination is the basic reason behind StackOverflowException for languages java, C, C++.

Stackoverflow exception is caused genrally in any language due to recursive method calls.

Suppose you have an method which is calling itself or any other method for an infinite recursive loop then it will cause a Stacoverflowexception. The reason behind this is the method call stack gets filled and it wont be able to accommodate any other method call.

Method call stack looks like this picture.

在这里输入图像描述

Explanation -- Suppose Main method has five statements And third method has an call to methodA, then the execution of main method gets paused at statement3 and MethosA will be loaded into call stack. Then method A has a call to methodB. So methodB also gets loaded into the stack.

So in this way infinite recursive calls makes call stack getting filled. So it cant afford any more methods. So it throws StackOverflowException.


For your code snippet, this is due to recursion method call:

public string Name
{
   get{ return Name; }
}

You are calling the Name method/property recursively. The stack fills up (with the parent Name method) until it overflows and a StackOverflowException is thrown.

链接地址: http://www.djcxy.com/p/80524.html

上一篇: 递归或迭代?

下一篇: 在C#,C ++和Java中导致堆栈溢出的最简单方法