string-util: add strdup_or_null() helper

This commit is contained in:
Lennart Poettering
2023-11-07 12:23:27 +01:00
parent 14ac242d50
commit 6a20a9d286
+21
View File
@@ -301,3 +301,24 @@ bool version_is_valid(const char *s);
bool version_is_valid_versionspec(const char *s);
ssize_t strlevenshtein(const char *x, const char *y);
static inline int strdup_or_null(const char *s, char **ret) {
char *c;
assert(ret);
/* This is a lot like strdup(), but is happy with NULL strings, and does not treat that as error, but
* copies the NULL value. */
if (!s) {
*ret = NULL;
return 0;
}
c = strdup(s);
if (!c)
return -ENOMEM;
*ret = c;
return 1;
}