From 5e71f86dffcd87a68ccb9e11a661d931e0e995e7 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Fri, 22 Sep 2023 22:22:12 +0200 Subject: [PATCH] alloc-util: add realloc0() helper than is like realloc() but zero-initializes appended space --- src/basic/alloc-util.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/basic/alloc-util.h b/src/basic/alloc-util.h index 156c973e692..3ef834aceee 100644 --- a/src/basic/alloc-util.h +++ b/src/basic/alloc-util.h @@ -254,4 +254,24 @@ static inline void free_many_charp(char **c, size_t n) { free_many((void**) c, n); } +_alloc_(2) static inline void *realloc0(void *p, size_t new_size) { + size_t old_size; + void *q; + + /* Like realloc(), but initializes anything appended to zero */ + + old_size = MALLOC_SIZEOF_SAFE(p); + + q = realloc(p, new_size); + if (!q) + return NULL; + + new_size = MALLOC_SIZEOF_SAFE(q); /* Update with actually allocated space */ + + if (new_size > old_size) + memset((uint8_t*) q + old_size, 0, new_size - old_size); + + return q; +} + #include "memory-util.h"