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.
This commit is contained in:
parent
f097883644
commit
2db3642b8d
1 changed files with 5 additions and 7 deletions
|
@ -8,13 +8,11 @@ strndup(char *p, size_t max)
|
|||
int n;
|
||||
char *np;
|
||||
|
||||
n = strlen(p)+1;
|
||||
if(n > max)
|
||||
n = max+1;
|
||||
np = malloc(n);
|
||||
n = strnlen(p, max);
|
||||
np = malloc(n+1);
|
||||
if(!np)
|
||||
return nil;
|
||||
memmove(np, p, n);
|
||||
np[n-1] = 0;
|
||||
return NULL;
|
||||
memcpy(np, p, n);
|
||||
np[n] = 0;
|
||||
return np;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue