th3g3ntl3man
th3g3ntl3man

Reputation: 2106

Python Api C generate memory leak

I have this simple code for run a small python code in C:

Py_Initialize();

string_module = PyUnicode_FromString((char *) "kmer_counter");
module = PyImport_Import(string_module);
function = PyObject_GetAttrString(module, (char *) "counter");
result = PyObject_CallFunction(function, "i", 5);

if ( !result ) {
    fprintf(stderr, "Exception:\n");
    PyErr_PrintEx(0);
    exit(1);
}

Py_DECREF(string_module);
Py_DECREF(module);
Py_DECREF(function);
Py_DECREF(result);

Py_Finalize();

I test the code with valgrind and I have memory leak (here the output). After some test I find that the memory leaks are caused by the istruction Py_Initialize();. How can I solve this problem?

I run valgrind with this flag:

valgrind --tool=memcheck --leak-check=full ./exe

Upvotes: 0

Views: 506

Answers (1)

phd
phd

Reputation: 3807

The output you have highlighted is (mostly) not memory leak, but rather invalid read. These are very probably caused by the very special way python manages its memory.

As part of the python source files, you should find a suppression file for valgrind, that should suppress these messages, as they are not real errors.

For my 3.6.6 python version, it is located in Python-3.6.6/Misc/valgrind-python.supp

So, run your program under valgrind using: valgrind --suppressions=path/to/the/python/Misc/valgrind-python.supp

You might also first need to do: export PYTHONMALLOC=malloc

Upvotes: 1

Related Questions