From e6a188b2e07683ad77e183d8131d1cb8f3fd0d20 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 20 Jun 2016 12:05:54 -0700 Subject: [PATCH] Fix memory leaks for Python dicts in C extension --- src/raylib.cc | 30 +++++++++++++++++++++++------- test/memory_leak_deserialize.py | 17 +++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) create mode 100644 test/memory_leak_deserialize.py diff --git a/src/raylib.cc b/src/raylib.cc index c727e67d4..87ca0d787 100644 --- a/src/raylib.cc +++ b/src/raylib.cc @@ -183,6 +183,20 @@ void TaskCapsule_Destructor(PyObject* capsule) { delete obj; } +// Helper methods + +// Pass ownership of both the key and the value to the PyDict. +// This is only required for PyDicts, not for PyLists or PyTuples, compare +// https://docs.python.org/2/c-api/dict.html +// https://docs.python.org/2/c-api/list.html +// https://docs.python.org/2/c-api/tuple.html + +void set_dict_item_and_transfer_ownership(PyObject* dict, PyObject* key, PyObject* val) { + PyDict_SetItem(dict, key, val); + Py_XDECREF(key); + Py_XDECREF(val); +} + // Serialization // serialize will serialize the python object val into the protocol buffer @@ -364,7 +378,9 @@ PyObject* deserialize(PyObject* worker_capsule, const Obj& obj, std::vector