Skip to content

Commit

Permalink
Fix memory leak when error occurs
Browse files Browse the repository at this point in the history
  • Loading branch information
jmao-denver committed Sep 22, 2023
1 parent 8dbf087 commit 58d345d
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/main/c/jpy_jbyte_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ extern "C" {
/**
* The Java ByteBuffer representation in Python.
*
* IMPORTANT: JPy_JByteBufferWrapper must only differ from the JPy_JObj structure by the 'obj' member
* IMPORTANT: JPy_JByteBufferWrapper must only differ from the JPy_JObj structure by the 'pyBuffer' member
* since we use the same basic type, name JPy_JType for it. DON'T ever change member positions!
* @see JPy_JObj
*/
Expand Down
9 changes: 7 additions & 2 deletions src/main/c/jpy_jobj.c
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,6 @@ int JType_InitSlots(JPy_JType* type)

isArray = type->componentType != NULL;
isPrimitiveArray = isArray && type->componentType->isPrimitive;
isByteBuffer = type == JPy_JByteBuffer;

typeObj = JTYPE_AS_PYTYPE(type);

Expand All @@ -734,7 +733,13 @@ int JType_InitSlots(JPy_JType* type)
//Py_SET_TYPE(type, &JType_Type);
//Py_SET_SIZE(type, sizeof (JPy_JType));

typeObj->tp_basicsize = isPrimitiveArray ? sizeof (JPy_JArray) : (isByteBuffer ? sizeof(JPy_JByteBufferWrapper) : sizeof (JPy_JObj));
if (isPrimitiveArray) {
typeObj->tp_basicsize = sizeof(JPy_JArray);
} else if (type == JPy_JByteBuffer) {
typeObj->tp_basicsize = sizeof(JPy_JByteBufferWrapper);
} else {
typeObj->tp_basicsize = sizeof(JPy_JObj);
}
typeObj->tp_itemsize = 0;
typeObj->tp_base = type->superType != NULL ? JTYPE_AS_PYTYPE(type->superType) : &JType_Type;
//typeObj->tp_base = (PyTypeObject*) type->superType;
Expand Down
3 changes: 3 additions & 0 deletions src/main/c/jpy_module.c
Original file line number Diff line number Diff line change
Expand Up @@ -691,16 +691,19 @@ PyObject* JPy_byte_buffer_internal(JNIEnv* jenv, PyObject* self, PyObject* args)

if (PyObject_GetBuffer(pyObj, pyBuffer, PyBUF_SIMPLE | PyBUF_C_CONTIGUOUS) != 0) {
PyErr_SetString(PyExc_ValueError, "byte_buffer: the Python object failed to return a contiguous buffer.");
PyMem_Free(pyBuffer);
return NULL;
}

byteBufferRef = (*jenv)->NewDirectByteBuffer(jenv, pyBuffer->buf, pyBuffer->len);
if (byteBufferRef == NULL) {
PyMem_Free(pyBuffer);
return PyErr_NoMemory();
}

newPyObj = JObj_New(jenv, byteBufferRef);
if (newPyObj == NULL) {
PyMem_Free(pyBuffer);
return NULL;
}
byteBufferWrapper = (JPy_JByteBufferWrapper *) newPyObj;
Expand Down

0 comments on commit 58d345d

Please sign in to comment.