简体   繁体   English

堆栈溢出异常中C ++和C#之间的区别

[英]Difference between c++ and c# in stack overflow exception

While I was writing some code in C#, I had a recursive method which caused a stack overflow exception after a couple thousand calls. 当我用C#编写一些代码时,我有一个递归方法,该方法在数千次调用后导致堆栈溢出异常。
So after a while, I wrote the same code in C++ and it worked fine with no exceptions (even though the actual number of recursive calls is about 10 times more than from where C# stopped). 因此,过了一会儿,我用C ++编写了相同的代码,并且在没有异常的情况下工作正常(即使递归调用的实际数量比C#停止处的实际数量大10倍左右)。
What is the difference between C# and C++ in handling this? C#和C ++在处理此问题上有什么区别? And is there any way I can allow for more recursive calls in C# without the exception being thrown? 有什么方法可以允许在C#中进行更多的递归调用而不会引发异常?

The most notable difference of stackoverflow in C# and C++ is: C++ doesn't have a "stack overflow exception" (*). C#和C ++中stackoverflow最明显的区别是:C ++没有“堆栈溢出异常”(*)。 The result of overflowing the stack with C++ is just undefined behavior. 用C ++溢出堆栈的结果只是未定义的行为。 It may do what you expect it to do but it may also do something entirely different. 它可能会执行您期望的操作,但是可能会执行完全不同的操作。 If you go lucky, the program crashes (with a segmentation violation because a protected page was allocated at the end of the stack) and if you go unlucky the stackoverflow isn't detected until at some point an attempt is made to access now overwritten memory. 如果运气不好,程序会崩溃(因为在堆栈的末尾分配了受保护的页面,所以会发生分段违规),如果运气不好,直到某个时候尝试访问现在被覆盖的内存,才会检测到堆栈溢出。

Other things which may factor into recursive calls: 可能会影响递归调用的其他因素:

  1. The available stack sizes may be different. 可用的堆栈大小可能不同。
  2. The sizes of the used stack frames are likely to be different. 使用的堆栈帧的大小可能会有所不同。
  3. Tail recursion optimizations may be done in one case but not the other. 尾递归优化可以在一种情况下完成,而在另一种情况下则不能。
  4. Some systems are capable of dynamically increasing their stack ("split stack"). 一些系统能够动态增加其堆栈(“拆分堆栈”)。

(*) As the behavior is undefined, some implementations may define a stackoverflow exception and throw that under appropriate conditions; (*)由于未定义行为,因此某些实现可能会定义stackoverflow异常并在适当的条件下抛出该异常; however, there is no such guarantee. 但是,没有这样的保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM