lib: Implement strndup()

Signed-off-by: Thierry Reding <treding@nvidia.com>
Signed-off-by: Tom Warren <twarren@nvidia.com>
This commit is contained in:
Thierry Reding 2019-04-15 11:32:14 +02:00 committed by Tom Warren
parent ebf30e8451
commit 0c4e2658e8
2 changed files with 24 additions and 0 deletions

View 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

View 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