简体   繁体   English

表达式评估-避免StackOverflow异常

[英]Expression evaluation - avoiding a StackOverflow Exception

I had been fiddling around to build my own expression evaluator and landed up at this issue i am curious about. 我一直在摆弄自己的表情评估器,并着手解决这个我很好奇的问题。

I have used 2 ways of evaluating a string expression. 我使用了两种评估字符串表达式的方法。 One method uses a Binary tree. 一种方法使用二叉树。

When i enter an expression string of length greater than (approx.) 42000, i get a stackoverflow exception. 当我输入长度大于(约)42000的表达式字符串时,出现堆栈溢出异常。

However the same does not happen if i evaluate the same expression string (even of much longer length) with this function (my second implementation) 但是同样的,如果我同样地进行评价表达字符串(甚至更长的时间长度)使用此功能(我的第二个实现)不会发生

Now i would prefer to stick to the Binary tree method - is there a way i can fix the Stack overflow exception, ie i can avoid my Stack overflow in recursion or is there a way to find when the Stack will actually overflow? 现在我更喜欢使用二叉树方法-有没有办法可以解决堆栈溢出异常,即我可以避免递归发生堆栈溢出,还是有办法找到堆栈实际何时会溢出? If not, how can i actually at least warn the user before even the expression starts getting evaluated that a Stack overflow can happen? 如果没有,我该如何实际上至少在甚至开始评估表达式可能发生堆栈溢出之前警告用户?

Honestly, your best bet is to use the second method. 老实说,最好的选择是使用第二种方法。 While a recursion is usable here, from an algorithm standpoint, the stack method that you provided is more correct - Mainly because your binary tree method doesn't have a way to deal with unary operators (as far as I can tell, at least) (eg, ++i). 尽管可以在此处使用递归,但从算法的角度来看,您提供的stack方法更正确-主要是因为您的二叉树方法没有处理一元运算符的方法(至少据我所知) (例如++ i)。

As for your first question, there isn't really a way to tell if something will throw a stack overflow exception from just input. 关于您的第一个问题,实际上并没有一种方法可以判断某些东西是否仅从输入中抛出堆栈溢出异常。 Your best bet would be to just wrap the first call to the recursive method in a try/catch, and explicitly catch the StackOverflowException, and return a valid error message to the user. 最好的选择是将第一个对递归方法的调用包装在try / catch中,并显式捕获StackOverflowException,然后向用户返回有效的错误消息。

Also, keep in mind, you could theoretically move the binary tree implementation to use a stack object similar to number 2, if you wanted. 另外,请记住,如果需要,理论上可以将二叉树实现移动为使用类似于数字2的堆栈对象。 Although you'd still have to redesign the method to use your stack instead of the application's stack. 尽管您仍然必须重新设计方法以使用堆栈而不是应用程序的堆栈。

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

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