Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!unhd.unh.edu!pas From: pas@unhd.unh.edu (Paul A. Sand) Newsgroups: comp.lang.c Subject: Re: realloc() (was: Re: Safe coding practices) Message-ID: <1991Feb9.032853.25461@unhd.unh.edu> Date: 9 Feb 91 03:28:53 GMT References: <00066@jimi.UUCP> Reply-To: pas@unhd.unh.edu (Paul A. Sand) Organization: University of New Hampshire Lines: 39 In article <00066@jimi.UUCP> rob@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@unhd.unh.edu |