From ee7db5067e4479d54507b7e5db816b0820d084f5 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Wed, 23 Oct 2024 11:54:50 +0000 Subject: [PATCH] util: Free pointer if it could not be reallocated Signed-off-by: Michael Tremer --- src/libpakfire/include/pakfire/util.h | 14 ++++++++++++++ src/libpakfire/util.c | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/libpakfire/include/pakfire/util.h b/src/libpakfire/include/pakfire/util.h index 4353b217a..7bb432b7c 100644 --- a/src/libpakfire/include/pakfire/util.h +++ b/src/libpakfire/include/pakfire/util.h @@ -35,6 +35,20 @@ #include #include +/* + This implementation of realloc frees the original buffer + if it could not be resized. +*/ +static inline void* pakfire_realloc(void* p, size_t size) { + void* n = realloc(p, size); + if (!n) { + if (p) + free(p); + } + + return n; +} + int pakfire_path_exists(const char* path); int pakfire_path_match(const char* p, const char* s); time_t pakfire_path_age(const char* path); diff --git a/src/libpakfire/util.c b/src/libpakfire/util.c index d884bb4da..b8798036b 100644 --- a/src/libpakfire/util.c +++ b/src/libpakfire/util.c @@ -971,7 +971,7 @@ int pakfire_b64decode(struct pakfire_ctx* ctx, void** output, size_t* length, ERR_error_string_n(ERR_get_error(), error, sizeof(error)); CTX_ERROR(ctx, "Could not read data: %s\n", error); - r = 1; + r = -EINVAL; goto ERROR; // Break if no more data could be read @@ -984,10 +984,10 @@ int pakfire_b64decode(struct pakfire_ctx* ctx, void** output, size_t* length, *length += bytes_read; // Allocate an output buffer - p = realloc(p, *length); + p = pakfire_realloc(p, *length); if (!p) { CTX_ERROR(ctx, "Could not allocate buffer: %m\n"); - r = 1; + r = -errno; goto ERROR; } -- 2.39.5