Skip to content Skip to sidebar Skip to footer

Memory Leak When Embedding Python Into My Application

The following program, when linked against python 2.7.13 and run on Windows 10 slowly but steadily leaks memory. #include #include int main() {

Solution 1:

Py_Finalize — Python/C API Reference Manual (emphasis mine):

<...> Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

Solution 2:

Above answer puts it all together

#include<Python.h>intmain(int argc, char *argv[]){
    Py_Initialize();
    wchar_t *name = Py_DecodeLocale(argv[0], NULL);
    Py_SetProgramName(name); 
    
    pythonlovesC();

    Py_Finalize();
    return0;
}

voidpythonlovesC(){

    while (true)
    {
       // do your python stuff here  PyGC_Collect();
        
    }

}

Post a Comment for "Memory Leak When Embedding Python Into My Application"