From ae429ebde2a0f88d1749a3ccd8f6b1251c6623e4 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Sun, 22 Mar 2026 23:36:25 +0100 Subject: [PATCH] lib/: memdup_T(): Add parameter 'n' I've found this to be useful elsewhere, where we want to duplicate an array. We need to implement this through a real memdup() function, because arrays can't be copied with the assignment operator ('='); we need to memcpy(3). Signed-off-by: Alejandro Colomar --- lib/string/strdup/memdup.c | 7 ++++++- lib/string/strdup/memdup.h | 40 +++++++++++++++++++++++++++----------- lib/utmp.c | 2 +- 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/lib/string/strdup/memdup.c b/lib/string/strdup/memdup.c index c574e3cff9..e4c41c6876 100644 --- a/lib/string/strdup/memdup.c +++ b/lib/string/strdup/memdup.c @@ -1,7 +1,12 @@ -// SPDX-FileCopyrightText: 2025, Alejandro Colomar +// SPDX-FileCopyrightText: 2025-2026, Alejandro Colomar // SPDX-License-Identifier: BSD-3-Clause #include "config.h" #include "string/strdup/memdup.h" + +#include + + +extern inline void *memdup(const void *p, size_t size); diff --git a/lib/string/strdup/memdup.h b/lib/string/strdup/memdup.h index cbae5158f8..d6df9e032e 100644 --- a/lib/string/strdup/memdup.h +++ b/lib/string/strdup/memdup.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2025, Alejandro Colomar +// SPDX-FileCopyrightText: 2025-2026, Alejandro Colomar // SPDX-License-Identifier: BSD-3-Clause @@ -9,21 +9,39 @@ #include "config.h" #include +#include +#include #include "alloc/malloc.h" +#include "attr.h" +#include "sizeof.h" // memdup_T - memory duplicate type-safe -#define memdup_T(p, T) memdup_T_(p, typeas(T)) -#define memdup_T_(p, T) \ -({ \ - T *new_; \ - \ - new_ = malloc_T(1, T); \ - if (new_ != NULL) \ - *new_ = *(p); \ - new_; \ -}) +#define memdup_T(p, n, T) memdup_T_(p, n, typeas(T)) +#define memdup_T_(p, n, T) \ +( \ + _Generic(p, T *: (void)0, const T *: (void)0), \ + (T *){memdup(p, (n) * sizeof(T))} \ +) + + +ATTR_MALLOC(free) +inline void *memdup(const void *p, size_t size); + + +// memdup - memory duplicate +inline void * +memdup(const void *p, size_t size) +{ + void *dup; + + dup = malloc(size); + if (dup == NULL) + return NULL; + + return memcpy(dup, p, size); +} #endif // include guard diff --git a/lib/utmp.c b/lib/utmp.c index dc9870a7cf..24ef049b9c 100644 --- a/lib/utmp.c +++ b/lib/utmp.c @@ -182,7 +182,7 @@ get_current_utmp(pid_t main_pid) ut = ut_by_pid ?: ut_by_line; if (NULL != ut) - ut = memdup_T(ut, struct utmpx); + ut = memdup_T(ut, 1, struct utmpx); free(ut_by_line); free(ut_by_pid);