什么是 StackOverflowError? [英] What is a StackOverflowError?

查看:24
本文介绍了什么是 StackOverflowError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是StackOverflowError,是什么导致的,我应该如何处理?

解决方案

参数和局部变量分配在上(引用类型,对象存在于> 和堆栈中的变量引用堆上的该对象).堆栈通常位于地址空间的端,当它用完时,它会朝向地址空间的底部(即朝向零).

您的流程还有一个,它位于流程的底部.当你分配内存时,这个堆可以向你的地址空间的上端增长.如您所见,堆有可能与堆碰撞"(有点像构造板块!!!).

堆栈溢出的常见原因是错误的递归调用.通常,这是由于您的递归函数没有正确的终止条件而导致的,因此它最终会永远调用自己.或者当终止条件很好时,可能是因为在满足它之前需要太多的递归调用.

但是,通过 GUI 编程,可以生成间接递归.例如,您的应用程序可能正在处理绘制消息,并且在处理它们时,它可能会调用一个函数,导致系统发送另一条绘制消息.在这里,您没有明确称呼自己,但 OS/VM 已经为您完成了.

要处理它们,您需要检查您的代码.如果你有调用自己的函数,那么检查你是否有一个终止条件.如果有,请检查在调用函数时是否至少修改了其中一个参数,否则递归调用的函数将没有可见的变化,并且终止条件是无用的.还要注意,在达到有效终止条件之前,您的堆栈空间可能会耗尽内存,从而确保您的方法可以处理需要更多递归调用的输入值.

如果您没有明显的递归函数,请检查您是否正在调用任何间接会导致您的函数被调用的库函数(如上面的隐式情况).

What is a StackOverflowError, what causes it, and how should I deal with them?

解决方案

Parameters and local variables are allocated on the stack (with reference types, the object lives on the heap and a variable in the stack references that object on the heap). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero).

Your process also has a heap, which lives at the bottom end of your process. As you allocate memory, this heap can grow towards the upper end of your address space. As you can see, there is a potential for the heap to "collide" with the stack (a bit like tectonic plates!!!).

The common cause for a stack overflow is a bad recursive call. Typically, this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself forever. Or when the termination condition is fine, it can be caused by requiring too many recursive calls before fulfilling it.

However, with GUI programming, it's possible to generate indirect recursion. For example, your app may be handling paint messages, and, whilst processing them, it may call a function that causes the system to send another paint message. Here you've not explicitly called yourself, but the OS/VM has done it for you.

To deal with them, you'll need to examine your code. If you've got functions that call themselves then check that you've got a terminating condition. If you have, then check that when calling the function you have at least modified one of the arguments, otherwise there'll be no visible change for the recursively called function and the terminating condition is useless. Also mind that your stack space can run out of memory before reaching a valid terminating condition, thus make sure your method can handle input values requiring more recursive calls.

If you've got no obvious recursive functions then check to see if you're calling any library functions that indirectly will cause your function to be called (like the implicit case above).

这篇关于什么是 StackOverflowError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆