realloc in buf_append

Niels Thykier niels at thykier.net
Sun Feb 17 15:54:23 EST 2013


On 2013-02-17 21:44, Kevin Cernekee wrote:
> On Sun, Feb 17, 2013 at 11:32 AM, Mike Miller <mtmiller at ieee.org> wrote:
> [...]
> 
> Good catch - this pattern shows up in a couple of places, e.g.
> 
> body = realloc(body, done + chunklen + 1);
> 
> *lineptr = realloc(*lineptr, *n);
> 
> opt = realloc(opt, sizeof(*opt) + opt->nr_choices * sizeof(*choice));
> 
> I wouldn't normally expect to be able to recover from exhausting the
> heap space anyway, since many other random library calls will start
> breaking.  But for the sake of argument would it make sense to wrap
> realloc() with something like this?
> 

I agree it is an unlikely case and yeah wrapping realloc can be done (I
have seen another upstream do something similar.

> int safe_realloc(void **ptr, size_t size)
> {
> 	void *newptr = realloc(*ptr, size);
> 	if (newptr) {
> 		*ptr = newptr;
> 		return 0;
> 	}
> 	free(*ptr);
Maybe insert:
        *ptr = NULL;

> 	return -ENOMEM;
> }

so a later free of *ptr will not crash the program.

~Niels





More information about the openconnect-devel mailing list