Python内存泄漏?

7
我正在撰写一个 Python 扩展,但似乎存在内存泄漏问题。我尝试使用 Valgrind 找出问题的源头。
然而,根据 Valgrind 的显示,Python 本身也存在内存泄漏问题。下面是一个简单的脚本:hello.py
  print "Hello World!"

并且执行

> valgrind --tool=memcheck python ./hello.py

(...)
==7937== ERROR SUMMARY: 580 errors from 34 contexts (suppressed: 21 from 1)
==7937== malloc/free: in use at exit: 721,878 bytes in 190 blocks.
==7937== malloc/free: 2,436 allocs, 2,246 frees, 1,863,631 bytes allocated.
==7937== For counts of detected errors, rerun with: -v
==7937== Use --track-origins=yes to see where uninitialised values come from
==7937== searching for pointers to 190 not-freed blocks.
==7937== checked 965,952 bytes.
==7937== 
==7937== LEAK SUMMARY:
==7937==    definitely lost: 0 bytes in 0 blocks.
==7937==      possibly lost: 4,612 bytes in 13 blocks.
==7937==    still reachable: 717,266 bytes in 177 blocks.
==7937==         suppressed: 0 bytes in 0 blocks.
==7937== Rerun with --leak-check=full to see details of leaked memory.

有人能解释这种奇怪的行为吗?Python解释器真的会泄漏内存吗?

Python开发者使用什么工具来调试他们的内存泄漏问题?

2个回答

12

Python源码中有一个完整的README.valgrind文件,解释了在尝试使用Valgrind调试Python时需要注意的各种问题:

http://svn.python.org/projects/python/trunk/Misc/README.valgrind

Python uses its own small-object allocation scheme on top of malloc,
called PyMalloc.

Valgrind may show some unexpected results when PyMalloc is used.
Starting with Python 2.3, PyMalloc is used by default.  You can disable
PyMalloc when configuring python by adding the --without-pymalloc option.
If you disable PyMalloc, most of the information in this document and
the supplied suppressions file will not be useful.  As discussed above,
disabling PyMalloc can catch more problems.

If you use valgrind on a default build of Python,  you will see
many errors like:

        ==6399== Use of uninitialised value of size 4
        ==6399== at 0x4A9BDE7E: PyObject_Free (obmalloc.c:711)
        ==6399== by 0x4A9B8198: dictresize (dictobject.c:477)

These are expected and not a problem. 

2

这个漏洞很可能来自于您自己的扩展,而不是来自Python。大型系统通常会在退出时仍然分配内存,因为如果进程即将结束,明确释放内存不值得。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接