realloc in buf_append

David Woodhouse dwmw2 at
Sun Feb 17 19:06:53 EST 2013

On Sun, 2013-02-17 at 12:44 -0800, Kevin Cernekee wrote:
> 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;
>         }
>         free(*ptr);
>         return -ENOMEM;
> }

I think I prefer a 'realloc_or_free' function which just *does* what
what all the existing code already expects: just free the original
pointer if it fails to allocate the new one.

void *safe_realloc(void *old, size_t size)
    void *p = realloc(old, size);
    if (size && !p)
    return p;

GnuTLS has a vaguely similar 'gnutls_realloc_fast()' function which it
doesn't export, and which doesn't free the original pointer if called
with a size argument of zero. Although I suspect the latter is a bug.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 6171 bytes
Desc: not available
URL: <>

More information about the openconnect-devel mailing list