diff options
| author | Rasmus Villemoes <[email protected]> | 2026-04-21 09:54:35 +0200 |
|---|---|---|
| committer | Tom Rini <[email protected]> | 2026-05-12 15:38:00 -0600 |
| commit | ee8be5d4a1035de232b3497563fe9f6773775f96 (patch) | |
| tree | c56925568ea459e1b7d151e0ad068f8b87e8573f /lib/string.c | |
| parent | 8c664d2135723a110a60b792a8614c4864ad82a3 (diff) | |
lib/string.c: implement strdup() and strndup() in terms of memdup_nul()
With the addition of memdup_nul(), strdup() and strndup() can be
implemented as one-liners.
While not required by POSIX or C, do keep the behaviour of gracefully
accepting a NULL source and simply return NULL.
Reviewed-by: Simon Glass <[email protected]>
Signed-off-by: Rasmus Villemoes <[email protected]>
Diffstat (limited to 'lib/string.c')
| -rw-r--r-- | lib/string.c | 30 |
1 files changed, 2 insertions, 28 deletions
diff --git a/lib/string.c b/lib/string.c index 3923cce5561..5ccd1011ab5 100644 --- a/lib/string.c +++ b/lib/string.c @@ -360,38 +360,12 @@ void *memdup_nul(const void *src, size_t len) char * strdup(const char *s) { - char *new; - - if ((s == NULL) || - ((new = malloc (strlen(s) + 1)) == NULL) ) { - return NULL; - } - - strcpy (new, s); - return new; + return s ? memdup_nul(s, strlen(s)) : NULL; } char * strndup(const char *s, size_t n) { - size_t len; - char *new; - - if (s == NULL) - return NULL; - - len = strlen(s); - - if (n < len) - len = n; - - new = malloc(len + 1); - if (new == NULL) - return NULL; - - strncpy(new, s, len); - new[len] = '\0'; - - return new; + return s ? memdup_nul(s, strnlen(s, n)) : NULL; } #ifndef __HAVE_ARCH_STRSPN |
