From 0c4e2658e8e8489956e48a6c9842c5d21b9593fe Mon Sep 17 00:00:00 2001 From: Thierry Reding Date: Mon, 15 Apr 2019 11:32:14 +0200 Subject: lib: Implement strndup() Signed-off-by: Thierry Reding Signed-off-by: Tom Warren --- lib/string.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'lib/string.c') diff --git a/lib/string.c b/lib/string.c index af17c16f61..9b779ddc3b 100644 --- a/lib/string.c +++ b/lib/string.c @@ -326,6 +326,29 @@ char * strdup(const char *s) } #endif +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; +} + #ifndef __HAVE_ARCH_STRSPN /** * strspn - Calculate the length of the initial substring of @s which only -- cgit v1.2.3