realloc in buf_append

Kevin Cernekee cernekee at
Sun Feb 17 15:44:36 EST 2013

On Sun, Feb 17, 2013 at 11:32 AM, Mike Miller <mtmiller at> wrote:
> A possible memory leak in the buf_append function was just reported
> [1]. At a glance it looks like most of the functions in http.c that
> use buf_append/buf_error will return ENOMEM back up the stack and
> openconnect will exit immediately. Users of the library should
> presumably do the same. I think it's still worth fixing to be safe,
> but do you see any possible conditions where this could be a problem?
> Thanks.
> [1]

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?

int safe_realloc(void **ptr, size_t size)
	void *newptr = realloc(*ptr, size);
	if (newptr) {
		*ptr = newptr;
		return 0;
	return -ENOMEM;

More information about the openconnect-devel mailing list