Python Forum
memory leak on embedded python in c++ - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: memory leak on embedded python in c++ (/thread-28359.html)



memory leak on embedded python in c++ - asdf3721 - Jul-15-2020

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();}
}


RE: memory leak on embedded python in c++ - Gribouillis - Jul-15-2020

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?


RE: memory leak on embedded python in c++ - asdf3721 - Jul-16-2020

(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?


RE: memory leak on embedded python in c++ - Gribouillis - Jul-16-2020

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.