bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: proper realloc(p,0) behavior?


From: Eric Blake
Subject: Re: proper realloc(p,0) behavior?
Date: Thu, 24 Mar 2011 13:47:04 -0600
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.15) Gecko/20110307 Fedora/3.1.9-0.39.b3pre.fc14 Lightning/1.0b3pre Mnenhy/0.8.3 Thunderbird/3.1.9

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   address@hidden    +1-801-349-2682
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]