[Top][All Lists]

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

realloc documentation

From: Pádraig Brady
Subject: realloc documentation
Date: Fri, 17 Apr 2009 11:24:19 +0100
User-agent: Thunderbird (X11/20071008)

I was looking at what was provided by the realloc module in gnulib
and was a bit confused. There was no texi info on it and the description
in modules/realloc just says "realloc() function that is glibc compatible".
For me, that wasn't enough info to infer how I should use realloc().

The module checks AC_FUNC_REALLOC which according to the autoconf docs,
checks that "realloc (NULL, 0)' returns a valid pointer".
I'm not sure that check is sufficient though.

I wrote a quick test program on glibc-2.7 to show:
  malloc (0)==valid_ptr
  realloc (valid_ptr,0)==NULL
  realloc (NULL,0)==valid_ptr
The interesting case there is the middle one which is not
covered by the AC_FUNC_REALLOC check as far as I can see.

So therefore on glibc _currently_ to handle errors from realloc()
we can do the following (this is what xrealloc() also checks):
  np = realloc (p, n);
  if (np==NULL && n) {
    free (p);
    error ();

Theoretically though, realloc(valid_ptr,0) could fail on
some platforms if an allocation is done. Thus the most
portable method is to check for ret=NULL && errno=ENOMEM.
Note realloc() on glibc doesn't reset errno to 0 in the
realloc(nonNULL,0) case. So one needs to:
  np = realloc (p, n);
  if (np==NULL && errno==ENOMEM) {
    free (p);
    error ();
I'm not sure that this is the actual desired interface though,
and as mentioned before, is not what xrealloc checks for at least.
It's too messy IMHO.

So what to change...

At least document what interface the realloc module is supposed to
provide without mentioning GLIBC as its implementation may change.
I guess the current GLIBC characteristics are what we should use?
I.E. add something like this to the docs:

  np = realloc (p, n);
  if (np==NULL && n) {
    free (p);
    error ();

Also at least document the caveat that we assume realloc(valid_ptr,0)
will never fail, but I guess it would be better to add a check that
realloc(valid_ptr,0)==NULL which would ensure this never happens.

I'll cook up a patch if the above sounds OK.


p.s. I also noticed the eealloc and safe-alloc modules which
look like alternative interfaces to work around these ambiguities.

reply via email to

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