Mail Archives: djgpp/2001/01/23/03:17:55
On Mon, 22 Jan 2001 23:42:33 -0500, DJ Delorie <dj AT delorie DOT com> wrote
in comp.os.msdos.djgpp:
>
> > >DJGPP's code allows this, but I didn't realize you could rely on it.
> >
> > Anyone up for a patch to the realloc() docs?
>
> I'd like to see a spec that says this is required behavior before we
> start encouraging people to use it.
Here is the text from the C99 standard:
7.20.3.4 The realloc function
Synopsis
[#1]
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
[#2] The realloc function deallocates the old object pointed
to by ptr and returns a pointer to a new object that has the
size specified by size. The contents of the new object
shall be the same as that of the old object prior to
deallocation, up to the lesser of the new and old sizes.
Any bytes in the new object beyond the size of the old
object have indeterminate values.
[#3] If ptr is a null pointer, the realloc function behaves
like the malloc function for the specified size. Otherwise,
if ptr does not match a pointer earlier returned by the
calloc, malloc, or realloc function, or if the space has
been deallocated by a call to the free or realloc function,
the behavior is undefined. If memory for the new object
cannot be allocated, the old object is not deallocated and
its value is unchanged.
Returns
[#4] The realloc function returns a pointer to the new
object (which may have the same value as a pointer to the
old object), or a null pointer if the new object could not
be allocated.
I use the C99 standard because I have a nicely formatted text version
for legible copy and paste. The wording is considerably expanded from
the original (ANSI-89 ISO-90 standard) because the original standard
wording left a few things out (like the original block is freed if
realloc() moves the memory).
But 7.10.3.4 (the section describing realloc() in the original C
standard) specifically contains this exact sentence:
"If the space cannot be allocated, the object pointed to by ptr is
unchanged."
So ANSI/ISO has always guaranteed that the original block is still
allocated and unmodified, and a pointer to it still valid (assuming
that you have one), if realloc() returns NULL when called with a valid
pointer.
The important thing, as Cesar pointed out, is to keep a separate copy
of the original copy so the null pointer return doesn't overwrite it,
causing a memory leak.
An additional reference, P. J. Plauger's C library reference at
http://www.dinkumware.com/htm_cl/stdlib.html#realloc.
I don't have source to DJGPP realloc() handy at the moment, but I
would be surprised if it did not follow the standard.
--
Jack Klein
Home: http://JK-Technology.Com
- Raw text -