This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: malloc attributes and realloc


> Can __attribute__((__malloc__)) safely be used on realloc-type functions?  

My answer would be "yes".

> glibc's <stdlib.h> has
> 
> extern void *realloc (void *__ptr, size_t __size) __THROW __attribute_malloc__;
> 
> while libiberty.h has
> 
> /* Reallocate memory without fail.  This works like xmalloc.  Note,
>    realloc type functions are not suitable for attribute malloc since
>    they may return the same address across multiple calls. */
> 
> extern PTR xrealloc PARAMS ((PTR, size_t));
> 
> - which is correct?

The C standard guarantees 7.20.3[#1]:

    Each such [one which has succeeded] allocation shall yield a
    pointer to an object disjoint from any other object.

Note that this applies to _all_ allocation functions calloc, malloc,
realloc.  Furthermore realloc is described as 7.20.3.4:

    The realloc function deallocates the old object pointed to by ptr
    and returns a pointer _to a new object_ [my emphasis] that has the
    size specified by size.

The case where an implementation chooses (as an optimization) to
return the same "new" pointer as its argument "old" pointer does not
matter, because any accesses to the old object through "old" or its
aliases are undefined.  The "old" object simply doesn't exist anymore.

> (Although the same value can be returned by realloc,
> the program can't compare the values as values without undefined behavior,
> only as bit patterns - and using them as bit patterns (a) involves taking
> the address of one of the pointers involved (possibly inhibiting
> optimization that way), (b) gets into the territory of DR#260.)

I cannot see how playing tricks with comparing bit patterns changes
any of the above.  Even if the program could portably detect the case
where the same value was returned by realloc(), that would not change
the fact that the old object doesn't exist any more and therefore
cannot have aliases.

Regards,
Wolfram.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]