From: Michael Tremer Date: Tue, 31 Dec 2024 11:52:35 +0000 (+0000) Subject: filelist: Fix removing items X-Git-Tag: 0.9.30~642 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=41d2678d55b6d7987d2ec38e85008cf44f20a403;p=pakfire.git filelist: Fix removing items This also now shrinks the array whenever possible so that we won't waste any memory if the filelist shrinks by a large amount. Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/filelist.c b/src/libpakfire/filelist.c index bac931411..b4f93ebd8 100644 --- a/src/libpakfire/filelist.c +++ b/src/libpakfire/filelist.c @@ -202,21 +202,29 @@ PAKFIRE_EXPORT int pakfire_filelist_add(struct pakfire_filelist* list, struct pa static int pakfire_filelist_remove(struct pakfire_filelist* list, struct pakfire_file* file) { // Check if the file is on the list - int i = pakfire_filelist_has_file(list, file); + int pos = pakfire_filelist_has_file(list, file); // Do nothing if the file is not on the list - if (i < 0) + if (pos < 0) return 0; // Remove the reference - pakfire_file_unref(list->files[i]); + pakfire_file_unref(list->files[pos]); // Fill the gap - memmove(list->files + i, list->files + i + 1, list->num_files - i - 1); + for (unsigned int i = pos; i < list->num_files - 1; i++) + list->files[i] = list->files[i + 1]; // The list is now shorter --list->num_files; + // Downsize the array + list->files = reallocarray(list->files, list->num_files, sizeof(*list->files)); + if (!list->files) { + ERROR(list->ctx, "Could not shrink the filelist: %m\n"); + return -errno; + } + return 0; }