[libc] Prevent strndup() from reading beyond the end of the string

strndup() may be called on a string which is not NUL-terminated.  Use
strnlen() instead of strlen() to ensure that we do not read beyond the
end of such a string.

Add self-tests for strndup(), including a test case with an
unterminated string.

Originally-fixed-by: Marin Hannache <git@mareo.fr>
Signed-off-by: Michael Brown <mcb30@ipxe.org>
This commit is contained in:
Michael Brown
2014-05-18 21:05:39 +01:00
parent 5249368950
commit 2b4be69eee
2 changed files with 21 additions and 3 deletions

View File

@@ -337,11 +337,9 @@ void * memchr(const void *s, int c, size_t n)
char * strndup(const char *s, size_t n)
{
size_t len = strlen(s);
size_t len = strnlen(s,n);
char *new;
if (len>n)
len = n;
new = malloc(len+1);
if (new) {
new[len] = '\0';