This is the mail archive of the
gdb-patches@sources.redhat.com
mailing list for the GDB project.
Re: [PATCH RFA] utils.c: Fix xcalloc (0, 0) behavior
- To: Andrew Cagney <ac131313 at cygnus dot com>
- Subject: Re: [PATCH RFA] utils.c: Fix xcalloc (0, 0) behavior
- From: Kevin Buettner <kevinb at cygnus dot com>
- Date: Mon, 5 Mar 2001 13:51:30 -0700
- Cc: gdb-patches at sources dot redhat dot com
- References: <1010303075808.ZM24102@ocotillo.lan> <3AA3F64E.9F0302A5@cygnus.com>
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