简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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