lib: Implement strndup()
authorThierry Reding <treding@nvidia.com>
Mon, 15 Apr 2019 09:32:14 +0000 (11:32 +0200)
committerTom Warren <twarren@nvidia.com>
Wed, 5 Jun 2019 16:16:32 +0000 (09:16 -0700)
Signed-off-by: Thierry Reding <treding@nvidia.com>
Signed-off-by: Tom Warren <twarren@nvidia.com>
include/linux/string.h
lib/string.c

index 36066207392e9c478b1e7a08c389ba34196827a3..5d63be4ce5b065a1b81fd57ca6612f04716af7db 100644 (file)
@@ -94,6 +94,7 @@ size_t strcspn(const char *s, const char *reject);
 #ifndef __HAVE_ARCH_STRDUP
 extern char * strdup(const char *);
 #endif
+extern char * strndup(const char *, size_t);
 #ifndef __HAVE_ARCH_STRSWAB
 extern char * strswab(const char *);
 #endif
index af17c16f616db4b8afc71cb55b31ad394457636b..9b779ddc3bbe42b6df36a70c3ece2213b40e5fa6 100644 (file)
@@ -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