🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #257

Re: pointers & order of execution

#257
From: Karl Heuer
Date: Tue, 20 Jun 1989 17:27
30 lines
2153 bytes
In article <844@cbnewsl.ATT.COM> dfp@cbnewsl.ATT.COM (david.f.prosser) writes:
>Any use of the value of t after the realloc call causes undefined behavior.

This is an important point, which I completely ignored in my own followup
(which was concerned with the order-of-evaluation question).  Clearly it's
meaningless to attempt to dereference a |free|'d pointer (including the old
value of a |realloc|'d pointer); but what's not as well known is that you
can't reliably do *anything* with that value anymore -- not even copy it into
a new variable, or compare it with |NULL|.

This allows for an implementation on a segmented architecture to have |malloc|
allocate a new segment from the system, and |free| return it.  If the hardware
distinguishes between arithmetic registers and address registers, and if
loading a bogus segment address into an address register causes a hardware
trap, then bad things could happen if the user does anything with a |free|'d
pointer.  So, in order to not place an undue burden on such implementations,
the pANS labels this as undefined behavior.

Hence, the correct way to synchronize mid-array pointers is:
	/* |b| is a |malloc|'d buffer; |c| points somewhere inside */
	something  *oldb = b;
	ptrdiff_t   dist = c - b;
	if ((b = (something *)realloc((void *)b, newsize)) == NULL) {
		b = oldb;  /* oldb is still valid, since |realloc| failed */
		fprintf(stderr, "sorry, no more space\n");
	} else {
		c = b + dist;
	}

Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint
Technical Details
Message-ID: <13765@haddock.ima.isc.com>
Path: arc1-ca.pugleaf.net!utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!ucbvax!decwrl!decvax!ima!haddock!karl
References: <920@tukki.jyu.fi> <921@tukki.jyu.fi> <844@cbnewsl.ATT.COM>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!ucbvax!decwrl!decvax!ima!haddock!karl
From: karl@haddock.ima.isc.com (Karl Heuer)
Newsgroups: comp.std.c
Subject: Re: pointers & order of execution
Summary: Dave's right; more details enclosed
Keywords: pointer subtraction, order of execution, realloc
Message-ID: <13765@haddock.ima.isc.com>
Date: 20 Jun 89 17:27:51 GMT
References: <920@tukki.jyu.fi> <921@tukki.jyu.fi> <844@cbnewsl.ATT.COM>
Reply-To: karl@haddock.ima.isc.com (Karl Heuer)
Organization: Interactive Systems, Boston
Lines: 30