libpayload/string: add strndup() function

Change-Id: Ie509e49f21fb537692704ac6527efa09649164e3
Signed-off-by: Thomas Heijligen <src@posteo.de>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/70115
Reviewed-by: Jakub Czapiga <jacz@semihalf.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
This commit is contained in:
Thomas Heijligen 2022-11-21 17:21:47 +01:00 committed by Felix Held
parent e68ddc71ef
commit 3d91563c98
2 changed files with 20 additions and 0 deletions

View File

@ -59,6 +59,7 @@ char *strcat(char *d, const char *s);
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
char *strdup(const char *s);
char *strndup(const char *s, size_t size);
char *strstr(const char *h, const char *n);
char *strsep(char **stringp, const char *delim);
size_t strspn(const char *s, const char *a);

View File

@ -321,6 +321,25 @@ char *strdup(const char *s)
return p;
}
/**
* Duplicate a string with a max length of size
*
* @param s The string to duplicate.
* @param size The max length of the string
* @return A pointer to the copy of the original string.
*/
char *strndup(const char *s, size_t size)
{
size_t n = strnlen(s, size);
char *p = malloc(n + 1);
if (p != NULL) {
strncpy(p, s, n);
p[n] = 0;
}
return p;
}
/**
* Find a substring within a string.
*