On 03/24/2011 01:02 PM, Jim Meyering wrote: >> It should be fairly easy to write code that is portable >> to both C89 and C99 and does not leak, by using free (p) rather >> than realloc (p, 0). For example, we could apply the following >> patch to xmalloc.c:
We can do whatever we want with xrealloc, since that can be documented
to behave how we want without regards to the underlying realloc()
semantics in effect.
>>
>> --- a/lib/xmalloc.c
>> +++ b/lib/xmalloc.c
>> @@ -52,10 +52,18 @@ xmalloc (size_t n)
>> void *
>> xrealloc (void *p, size_t n)
>> {
>> - p = realloc (p, n);
>> - if (!p && n != 0)
>> - xalloc_die ();
>> - return p;
>> + if (n)
>> + {
>> + p = realloc (p, n);
>> + if (!p)
>> + xalloc_die ();
>> + return p;
>> + }
>> + else
>> + {
>> + free (p);
>> + return NULL;
>> + }
>> }
No argument by me if we enforce saner semantics to xrealloc.
>>
>> /* If P is null, allocate a block of at least *PN bytes; otherwise,
>
> Good idea.
> Maybe write it like this instead?
>
> if (n == 0)
> {
> free (p);
> return NULL;
> }
>
> p = realloc (p, n);
> if (!p)
> xalloc_die ();
> return p;
>
> -------------
> or like this?
> -------------
>
> if (n == 0)
> {
> free (p);
> p = NULL
Needs ;
> }
> else
> {
> p = realloc (p, n);
> if (!p)
> xalloc_die ();
> }
> return p;
Those variations all look equally legible to me; I don't have any
preference on which form it takes.
> FYI, I searched for examples with a literal 0, using this:
>
>
> http://codesearch.google.com/codesearch?sa=N&q=realloc\+*\%28[^,],\+*0\%29%3B
>
> This is the only significant hit:
>
> daikon/kvasir/valgrind/massif/tests/realloc.c - 5 identical
> 16: x = realloc(x, 0); // equivalent to free(x), and ends up
> 17: // calling Valgrind's (and Massif's)
> free
> pag.csail.mit.edu/daikon/download/daikon.tar.gz - GPL - C
>
> There are plenty of others, but they're in configure tests.
I'm also thinking of writing a systemtap probe for realloc(,0) with a
goal of running it on my typical Linux workload to see how many
violations happen in practice. I'll post it if I get it working.
--
Eric Blake [email protected] +1-801-349-2682
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature
