Samvel Hovsepyan
Samvel Hovsepyan

Reputation: 659

What is the correct way python memory management in case of exceptions?

I am writing my own Python module and need some advice. Let's consider an example function in a module:

PyObject* my_func(PyObject *self, PyObject* args)
{
    PyObject* returnObj;
    try
    {
       returnObj = my_create_output();
    }
    catch(const std::exception& ex)
    {
        PyErr_SetString(PyExc_Exception, ex.what());
        returnObj = NULL;
    }
    return returnObj;
}

my_create_output function can raise different exceptions (also my own exceptions). returnObj is a big structure (for example, a list) and it may happen that my_create_output function will raise an exception when half of the output is already created. How should I delete the allocated objects in the catch block for such cases?

Upvotes: 2

Views: 58

Answers (1)

user2357112
user2357112

Reputation: 281476

my_create_output should handle the deallocation of everything it creates in the case of an exception, as a caller catching the exception has no way to access any of it.

Upvotes: 2

Related Questions