c++-to-python swig caused memory leak! Related to Py_BuildValue and SWIG_NewPointerObj
- by usfree74
Hey gurus,
I have the following Swig code that caused memory leak.
PyObject* FindBestMatch(const Bar& fp) {
Foo* ptr(new Foo());
float match;
// call a function to fill the foo pointer
return Py_BuildValue(
"(fO)",
match,
SWIG_NewPointerObj(ptr,
SWIGTYPE_p_Foo,
0 /* own */));
}
I figured that ptr is not freed properly. So I did the following:
PyObject* FindBestMatch(const Bar& fp) {
Foo* ptr(new Foo());
float match;
// call a function to fill the foo pointer
*PyObject *o = SWIG_NewPointerObj(ptr,
SWIGTYPE_p_Foo,
1 /* own */);* <------- 1 means pass the ownership to python
PyObject *result = Py_BuildValue("(fO)", match, o);
Py_XDECREF(o);
return result;
}
But I am not very sure whether this will cause memory corruption. Here, Py_XDECREF(o) will decrease the ref count, which can free memory used by object "o". But o is part of the return value "result". Freeing "o" can cause data corrupt, I guess?
I tried my change. It works fine and the caller (python code) does see the expected data. But this could be because nobody else overwrites to that memory area.
So what's the right way to deal with memory management of the above code? I search the swig docs, but don't see very concrete description.
Please help!
Thanks,
xin