From: Michael Tremer Date: Fri, 9 Jul 2021 10:19:58 +0000 (+0000) Subject: _pakfire: Fix memory leaks in generating key lists X-Git-Tag: 0.9.28~1067 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=11fdddfa8b734a7ca189ecf2afda2529fc6f0455;p=pakfire.git _pakfire: Fix memory leaks in generating key lists Signed-off-by: Michael Tremer --- diff --git a/src/_pakfire/pakfire.c b/src/_pakfire/pakfire.c index 9cdf190f4..a8b9f944d 100644 --- a/src/_pakfire/pakfire.c +++ b/src/_pakfire/pakfire.c @@ -407,23 +407,28 @@ static PyObject* Pakfire_update(PakfireObject* self, PyObject* args, PyObject* k Py_RETURN_NONE; } -static PyObject* _import_keylist(PakfireObject* pakfire, struct pakfire_key** keys) { +static PyObject* Pakfire_keys_to_list(struct pakfire_key** keys) { PyObject* list = PyList_New(0); - while (keys && *keys) { - struct pakfire_key* key = *keys++; + // Empty input? + if (!keys) + return list; - PyObject* object = new_key(&KeyType, key); - PyList_Append(list, object); + // Push all keys onto the list + for (struct pakfire_key** key = keys; *key; key++) { + PyObject* object = new_key(&KeyType, *key); + if (!object) + goto ERROR; - // Drop reference to the Python object + PyList_Append(list, object); Py_DECREF(object); - - // Drop reference to the key object - pakfire_key_unref(key); } return list; + +ERROR: + Py_DECREF(list); + return NULL; } static PyObject* Pakfire_get_keys(PakfireObject* self) { @@ -435,8 +440,15 @@ static PyObject* Pakfire_get_keys(PakfireObject* self) { return NULL; } -#warning THIS LEAKS MEMORY - return _import_keylist(self, keys); + // Convert keys to list + PyObject* list = Pakfire_keys_to_list(keys); + + // Free keys + for (struct pakfire_key** key = keys; *key; key++) + pakfire_key_unref(*key); + free(keys); + + return list; } static PyObject* Pakfire_get_key(PakfireObject* self, PyObject* args) { @@ -498,8 +510,15 @@ static PyObject* Pakfire_import_key(PakfireObject* self, PyObject* args) { return NULL; } -#warning THIS LEAKS MEMORY - return _import_keylist(self, keys); + // Convert keys to list + PyObject* list = Pakfire_keys_to_list(keys); + + // Free keys + for (struct pakfire_key** key = keys; *key; key++) + pakfire_key_unref(*key); + free(keys); + + return list; } static PyObject* Pakfire_fetch_key(PakfireObject* self, PyObject* args, PyObject* kwds) {