realloc() (was: Re: Safe coding practices)

Paul A. Sand pas at unhd.unh.edu
Sat Feb 9 14:28:53 AEST 1991


In article <00066 at jimi.UUCP> rob at jimi.UUCP writes:
[me:]
>>But as long as I'm reading, I did notice a howler in Jaeschke's text,
>>on page 320:
>>
>>	You should ALWAYS use realloc as follows:
>>
>>	ptr = realloc(ptr, new_size);
>>

>  My understanding has always been that if realloc() fails (returns NULL),
>ALL access to the previously allocated block is gone. It makes no difference
>whether you keep the original ptr or not.

An ANSI-compatible realloc() must keep the original block unchanged on
failure. (See K&R, 2nd ed., p. 252.) Jaeschke's code is OK if you
assume that the block is trashed, but less than ideal if you're using a
standard realloc(). For that reason, I don't think he should have
said "ALWAYS".

>  This has stuck in my head because of a particularly nasty bug due to
>assuming that the original ptr was still valid after the failure. But I can't
>seem to find an adequate reference to back up my 'understanding'.

Since my original posting, a number of folks have pointed out that some
older realloc()'s indeed do trash the original block on failure.  My
own research (read: "a few minutes browsing at the bookstores") bears
this out. One text claims that the UNIX System V Release 4 realloc()
acts like that. (Can that be true?)

Interestingly enough, none of the three books I use as portability
references bothers to point this out, which is regrettable. Grr.
(Jaeschke's _Portability and the C Language_; Rabinowitz & Schaap's
_Portable C_, and Harbison & Steele, 3rd ed.)
-- 
-- Paul A. Sand                |
-- University of New Hampshire | I ain't here on business, baby.
-- uunet!unhd!pas              | I'm only here for fun.
-- pas at unhd.unh.edu            |



More information about the Comp.lang.c mailing list