From 34ea3f804f80d7d385b8d410e11093b8a2b85e8d Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Sat, 22 Feb 2025 16:01:51 +0000 Subject: [PATCH] file: Refactor making the filelist There seems to have been a leak when initializing the string, so we format it on the stack first and then copy it to the heap later. Signed-off-by: Michael Tremer --- src/pakfire/file.c | 44 ++++++++++++++++---------------------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/src/pakfire/file.c b/src/pakfire/file.c index 19014b18..35e47af5 100644 --- a/src/pakfire/file.c +++ b/src/pakfire/file.c @@ -702,26 +702,20 @@ static int __pakfire_file_strmode(struct pakfire_file* file, char* s, const size } char* pakfire_file_dump(struct pakfire_file* file, int flags) { - char* buffer = NULL; - int r; - + char buffer[LINE_MAX] = ""; char mode[12]; char time[32]; - - // Initialize the buffer - r = asprintf(&buffer, "%s", ""); - if (r < 0) - goto ERROR; + int r; // Format mode if (flags & PAKFIRE_FILE_DUMP_MODE) { r = pakfire_file_strmode(file, mode); if (r) - goto ERROR; + return NULL; - r = asprintf(&buffer, "%s %s", buffer, mode); + r = pakfire_string_appendf(buffer, " %s", mode); if (r < 0) - goto ERROR; + return NULL; } // Format ownership @@ -729,18 +723,18 @@ char* pakfire_file_dump(struct pakfire_file* file, int flags) { const char* uname = pakfire_file_get_uname(file); const char* gname = pakfire_file_get_gname(file); - r = asprintf(&buffer, "%s %s/%s", buffer, uname, gname); + r = pakfire_string_appendf(buffer, " %s/%s", uname, gname); if (r < 0) - goto ERROR; + return NULL; } // Format size if (flags & PAKFIRE_FILE_DUMP_SIZE) { const size_t size = pakfire_file_get_size(file); - r = asprintf(&buffer, "%s %8zu", buffer, size); + r = pakfire_string_appendf(buffer, " %8zu", size); if (r < 0) - goto ERROR; + return NULL; } // Format time @@ -749,23 +743,23 @@ char* pakfire_file_dump(struct pakfire_file* file, int flags) { r = pakfire_strftime(time, "%Y-%m-%d %H:%M", ctime); if (r) - goto ERROR; + return NULL; - r = asprintf(&buffer, "%s %s", buffer, time); + r = pakfire_string_appendf(buffer, " %s", time); if (r < 0) - goto ERROR; + return NULL; } // Format path - r = asprintf(&buffer, "%s %s", buffer, pakfire_file_get_path(file)); + r = pakfire_string_appendf(buffer, " %s", pakfire_file_get_path(file)); if (r < 0) - goto ERROR; + return NULL; // Append symlink target if (flags & PAKFIRE_FILE_DUMP_LINK_TARGETS) { switch (pakfire_file_get_type(file)) { case S_IFLNK: - r = asprintf(&buffer, "%s -> %s", buffer, pakfire_file_get_symlink(file)); + r = pakfire_string_appendf(buffer, " -> %s", pakfire_file_get_symlink(file)); if (r < 0) return NULL; @@ -774,13 +768,7 @@ char* pakfire_file_dump(struct pakfire_file* file, int flags) { } } - return buffer; - -ERROR: - if (buffer) - free(buffer); - - return NULL; + return strdup(buffer); } int pakfire_file_cmp(struct pakfire_file* file1, struct pakfire_file* file2) { -- 2.39.5