Python Forum

Full Version: memory leak on embedded python in c++
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
why this line cause memory?
how do I solve it

void cyc()
{
Py_Initialize();


PyObject *pArgs = Py_BuildValue("idd",4,1.0,1.0);

Py_DECREF(pArgs);


Py_Finalize(); //memory leak why?
}

int main()
{
for(;;)
{cyc();}
}
I don't know why there is a memory leak, but normal C programs call Py_Initialize() and Py_Finalize() only once. Why would anyone want to call them in a loop?
(Jul-15-2020, 10:02 PM)Gribouillis Wrote: [ -> ]I don't know why there is a memory leak, but normal C programs call Py_Initialize() and Py_Finalize() only once. Why would anyone want to call them in a loop?

I've test on OS X 10.15 with python 3.8.3, there is a memory leak.
Do you mean that I should not using Py_Initialize and Py_Finalize in C function? so that I should not use them multi times?
I'm not saying that you must never call them several times, but I don't see a good reason for calling them a very large number of times.

The documentation of Py_FinalizeEx() says
Quote: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_FinalizeEx() more than once.