strndup: don't assume buffer is terminated

Using strlen in strndup will walk past the first
n bytes up to the terminator, which may not be
present. This is not what we want.

While we're here, do some cleanups.
front
Ori Bernstein 2020-12-18 07:16:29 -08:00
parent f097883644
commit 2db3642b8d
1 changed files with 5 additions and 7 deletions

View File

@ -8,13 +8,11 @@ strndup(char *p, size_t max)
int n; int n;
char *np; char *np;
n = strlen(p)+1; n = strnlen(p, max);
if(n > max) np = malloc(n+1);
n = max+1;
np = malloc(n);
if(!np) if(!np)
return nil; return NULL;
memmove(np, p, n); memcpy(np, p, n);
np[n-1] = 0; np[n] = 0;
return np; return np;
} }