Implement reallocarray()
Stateless and I stumbled upon this issue while discussing the semantics of read, accepting a size_t but only being able to return ssize_t, effectively lacking the ability to report successful reads > SSIZE_MAX. The discussion went along and we came to the topic of input-based memory allocations. Basically, it was possible for the argument to a memory-allocation-function to overflow, leading to a segfault later. The OpenBSD-guys came up with the ingenious reallocarray-function, and I implemented it as ereallocarray, which automatically returns on error. Read more about it here[0]. A simple testcase is this (courtesy to stateless): $ sbase-strings -n (2^(32|64) / 4) This will segfault before this patch and properly return an OOM- situation afterwards (thanks to the overflow-check in reallocarray). [0]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/calloc.3
This commit is contained in:
7
sed.c
7
sed.c
@@ -275,7 +275,7 @@ resize(void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next)
|
||||
void *n, *tmp;
|
||||
|
||||
if (new_nmemb) {
|
||||
tmp = erealloc(*ptr, new_nmemb * size);
|
||||
tmp = ereallocarray(*ptr, new_nmemb, size);
|
||||
} else { /* turns out realloc(*ptr, 0) != free(*ptr) */
|
||||
free(*ptr);
|
||||
tmp = NULL;
|
||||
@@ -596,7 +596,10 @@ chompr(char *s, Rune rune)
|
||||
Rune *
|
||||
strtorunes(char *s, size_t nrunes)
|
||||
{
|
||||
Rune *rs = emalloc(sizeof(*rs) * nrunes + 1), *rp = rs;
|
||||
Rune *rs = NULL, *rp;
|
||||
|
||||
rs = ereallocarray(rs, nrunes + 1, sizeof(*rs));
|
||||
rp = rs;
|
||||
|
||||
while (nrunes--)
|
||||
s += chartorune(rp++, s);
|
||||
|
Reference in New Issue
Block a user