From 44245e4684be1fac6c2fb7ac67dce8a55a574956 Mon Sep 17 00:00:00 2001 From: "H. Peter Anvin (Intel)" Date: Fri, 26 Jun 2026 17:25:23 -0700 Subject: [PATCH] Add nasm_strdupto() and nasm_strto(), to replace a string variable It is common enough that one wants to set a string pointer to a newly allocated string, freeing the old one if it is not NULL. Add specific helper functions for this. Signed-off-by: H. Peter Anvin (Intel) --- include/nasmlib.h | 23 +++++++++++++++++++++++ nasmlib/alloc.c | 11 +++++++++++ 2 files changed, 34 insertions(+) diff --git a/include/nasmlib.h b/include/nasmlib.h index ea0a880b9..529fb0660 100644 --- a/include/nasmlib.h +++ b/include/nasmlib.h @@ -102,6 +102,29 @@ char * safe_alloc nasm_strndup(const char *, size_t); char * safe_alloc nasm_strcat(const char *one, const char *two); char * safe_alloc end_with_null nasm_strcatn(const char *one, ...); +/* + * Replace a string in a string pointer variable with a nasm_strdup() + * copy of the argument on the right, freeing the contents of the + * previous contents of the variable if non-NULL. + * + * If *str is NULL, simply return the old value of *ptrp. + */ +char *nasm_strdupto(char **ptrp, const char *str); + +/* + * Similar, but the new pointer must already have been heap allocated + * by the creating function. + */ +static inline char *nasm_strto(char **ptrp, char *str) +{ + char *ptr = *ptrp; + if (!str) + return ptr; + if (ptr) + nasm_free(ptr); + return *ptrp = str; +} + /* * nasm_[v]asprintf() are variants of the semi-standard [v]asprintf() * functions, except that we return the pointer instead of a count. diff --git a/nasmlib/alloc.c b/nasmlib/alloc.c index 32e181e76..71570a33b 100644 --- a/nasmlib/alloc.c +++ b/nasmlib/alloc.c @@ -99,6 +99,17 @@ char *nasm_strndup(const char *s, size_t len) return memcpy(p, s, len); } +char *nasm_strdupto(char **ptrp, const char *str) +{ + char *ptr = *ptrp; + if (str) { + if (ptr) + nasm_free(ptr); + *ptrp = ptr = nasm_strdup(str); + } + return ptr; +} + char *nasm_strcat(const char *one, const char *two) { char *rslt;