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
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue