From an unexpected Stack Overflow exception (1)

Source: Internet
Author: User

Today, a friend told me thatProgramStackoverflowexception

However, if you do not know why, it is just a recursion.CodeIt seems no problem for a few people to read it.

The following is the simplified code (the actual code is much more complicated, but the general idea is as follows)

 
Static VoidTest (IntI)
{
If(I>20000) // Or other exit conditions
{
Return;
}
Test (I +1);
}

Static VoidMain ()
{
Test (0);
}

What's the problem? Tip: there are no logic problems, and do not look for any syntax errors.

It looks like the logic is: This Code does not have an endless loop, so it exits 20000 times,

However, an stackoverflowexception exception is thrown during actual operation,

The reason is that the default stack size in the CLR is 1 MB,

This program is continuously recursive, and each level of recursive method is pushed into the stack. When the stack size reaches 1 MB, stackoverflowexception throws

Stack Overflow is thrown when I run to 15918 on my machine.

You may think that recursion is performed more than 10000 times. It seems that there should be no problems.

In fact, as long as you are not careful, hundreds of times of recursion will cause exceptions.

This will be demonstrated later...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.