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) <hpa@zytor.com>
This commit is contained in:
H. Peter Anvin (Intel) 2026-06-26 17:25:23 -07:00
parent 7b4e77dae2
commit 44245e4684
2 changed files with 34 additions and 0 deletions

View file

@ -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.

View file

@ -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;