Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use valgrind with Python C++ extensions?

I have Python extensions implemented on C++ classes. I don't have a C++ target to run valgrind with. I want to use valgrind for memory check.

Can I use valgrind with Python?

like image 601
neuron Avatar asked Oct 20 '10 20:10

neuron


People also ask

Can you use valgrind with python?

Valgrind is used periodically by Python developers to try to ensure there are no memory leaks or invalid memory reads/writes. If you want to use Valgrind more effectively and catch even more memory leaks, you will need to configure python --without-pymalloc.

What is valgrind Linux?

Valgrind (/ˈvælɡrɪnd/) is a programming tool for memory debugging, memory leak detection, and profiling. Valgrind. Original author(s) Julian Seward. Developer(s)


2 Answers

Yes, you can use valgrind with Python. You just need to use the valgrind suppression file provided by the Python developers, so you don't get a bunch of false positives due to Python's custom memory allocation/reallocation functions.

The valgrind suppression file can be found here: http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp

IMPORTANT: You need to uncomment the lines for PyObject_Free and PyObject_Realloc in the suppression file*.

The recommended usage syntax is:

$ valgrind --tool=memcheck --suppressions=valgrind-python.supp \                                           python -E -tt ./my_python_script.py 

See also this README file from the Python SVN repo which describes the different ways of using Python with valgrind: http://svn.python.org/projects/python/trunk/Misc/README.valgrind

* - Alternatively, you can recompile Python with PyMalloc disabled, which allows you to catch more memory leaks that won't show up if you just suppress PyMalloc.

like image 52
Steven T. Snyder Avatar answered Sep 21 '22 01:09

Steven T. Snyder


In Python 2.7 and 3.2 there is now a --with-valgrind compile-time flag that allows the Python interpreter to detect when it runs under valgrind and disables PyMalloc. This should allow you to more accurately monitor your memory allocations than otherwise, as PyMalloc just allocates memory in big chunks.

like image 33
Kamil Kisiel Avatar answered Sep 23 '22 01:09

Kamil Kisiel