This is the mail archive of the gdb-patches@sources.redhat.com mailing list for the GDB project.


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

Re: [PATCH RFA] utils.c: Fix xcalloc (0, 0) behavior


On Mar 5,  3:25pm, Andrew Cagney wrote:

> Kevin Buettner wrote:
> > 
> > According to section 16.1 in Harbison & Steele, it is permissible for
> > calloc(0,0) to return either NULL or an implementation defined unique
> > pointer.  I've come across an implementation of calloc() which chooses
> > to return NULL.
> 
> Does anyone know what the ISO-C standard has to say?

The following is from the August 3, 1998 Committe Draft of WG14/N843...

    7.20.3 Memory management functions

    The order and contiguity of storage allocated by successive calls
    to the calloc, malloc, and realloc functions is unspecified.  The
    pointer returned if the allocation succeeds is suitably aligned so
    that it may be assigned to a pointer to any type of object and
    then used to access such an object or an array of such objects in
    the space allocated (until the space is explicitly freed or
    reallocated).  Each such allocation shall yield a pointer to an
    object disjoint from any other object.  The pointer returned
    points to the start (lowest byte address) of the allocated space. 
    If the space cannot be allocated, a null pointer is returned.  If
    the size of the space requested is zero, the behavior is
    implementation-defined:  either a null pointer is returned, or the
    behavior is as if the size were some nonzero value, except that
    the returned pointer shall not be used to access an object.  The
    value of a pointer that refers to freed space is indeterminate.

> I think it would be helpful if xcalloc() not only followed ISO-C but
> also did it in a consistent way across platforms.

In separate email to David Taylor and Peter Schauer, I suggested an
alternate implementation of xcalloc().  Peter was concerned that there
might be some breakage due to the fact that callers of xcalloc() (and
other memory allocation functions) presently expect to get back
non-NULL results.  I don't know if this is actually a problem or not,
but forcing NULL to be returned for zero-sized allocations on all
platforms would cause any problems to be found a lot sooner.

PTR
xcalloc (size_t number, size_t size)
{
  void *mem;
  
  if (number == 0 || size == 0)
    mem = NULL;
  else {
    mem = mcalloc (NULL, number, size);
    if (mem == NULL)
      nomem (number * size);
  }
  return mem;
}

I think this provides the desired consistency across platforms.  I'll
post a new patch shortly.

Kevin


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