From: Karel Zak Date: Wed, 26 Jun 2019 14:47:24 +0000 (+0200) Subject: include/strutils: add strrealloc() X-Git-Tag: v2.35-rc1~151 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=23afadca57cb68ba4f6fead08b23f6fe6910c9e3;p=thirdparty%2Futil-linux.git include/strutils: add strrealloc() --- diff --git a/include/strutils.h b/include/strutils.h index d1f3da1b65..963e3d6f4c 100644 --- a/include/strutils.h +++ b/include/strutils.h @@ -93,6 +93,37 @@ static inline char *mem2strcpy(char *dest, const void *src, size_t n, size_t nma return dest; } +/* Reallocate @str according to @newstr and copy @newstr to @str; returns new @str */ +static inline char * __attribute__((warn_unused_result)) +strrealloc(char *str, const char *newstr) +{ + size_t nsz, osz; + + if (!str) + return newstr ? strdup(newstr) : NULL; + if (!newstr) { + free(str); + goto nothing; + } + + osz = strlen(str); + nsz = strlen(newstr); + + if (nsz > osz) { + char *tmp = realloc(str, nsz + 1); + if (!tmp) + goto nothing; + str = tmp; + } + + memcpy(str, newstr, nsz + 1); + return str; + +nothing: + free(str); + return NULL; +} + static inline int strdup_to_offset(void *stru, size_t offset, const char *str) { char *n = NULL;