为什么python的eval有长度限制? [英] Why is there a length limit to python's eval?

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

问题描述

我不主张这样做将​​是一个好主意,但我发现,通过在 eval 上运行,可以使Python崩溃(2.7和3.2选中)一个足够大的输入字符串:

I'm not advocating that this would ever be a good idea, but I've found that you can crash Python (2.7 and 3.2 checked) by running eval on a large enough input string:

def kill_python(N):
    S = '+'.join((str(n) for n in xrange(N)))
    return eval(S)

在我的计算机上,可以很好地生成 S ,但是对于大约 N> 74900 的值,Python将失败,并显示分段错误(核心已转储)。解释器可以处理的字符串(或解析树)的长度是否有限制?

On my computer S can be generated just fine, but for values of approximately N>74900, Python will fail with Segmentation fault (core dumped). Is there a limit to the length of string (or parse tree) that the interpreter can handle?

注意:我不需要这样做,对我来说,这是一个更深层次的问题,反映了我的无知盒子里面发生的事情我想了解Python为什么在这里失败,并且如此灾难性(为什么不引发异常?)

Note: I don't need to do this, to me this is a deeper question reflecting my ignorance of what goes on inside the box. I'd like to understand why Python fails here, and so catastrophically (why not throw an exception?)

推荐答案

由CPython编译器中的堆栈溢出引起。重现相同问题的简单方法是

This issue is caused by a stack overflow in the CPython compiler. An easy way to reproduce the same issue is

>>> code = compile("1" + "+1" * 1000000, "", "eval")
Segmentation fault

证明段错误发生在编译阶段,而不是在评估阶段。 (当然,也可以使用gdb轻松确认。)

which proves that the segfault is happening at the compile stage, not during evaluation. (Of course this is also easy to confirm with gdb.)

[注意:对于较小的表达式,编译器无论如何都会在此处应用常量折叠,因此唯一发生的事情是在执行代码期间将加载结果:

[Side note: For smaller expressions, the compiler would apply constant folding here anyway, so the only thing happening during the execution of the code is to load the result:

>>> code = compile("1" + "+1" * 1000, "", "eval")
>>> eval(code)
1001
>>> dis.dis(code)
  1           0 LOAD_CONST            1000 (1001)
              3 RETURN_VALUE        

便笺结尾。]

此问题是已知缺陷。 Python开发人员在目录<$中收集了几种使Python解释器崩溃的方法。 c $ c>库/测试/崩溃 。与此问题相对应的是 lib / test / crashers / compiler_recursion.py

This issue is a known defect. The Python developers collected several ways to crash the Python interpreter in the directory Lib/test/crashers of the source distribution. The one corresponding to this issue is Lib/test/crashers/compiler_recursion.py.

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

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