Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!cbnewsl!dfp From: dfp@cbnewsl.ATT.COM (david.f.prosser) Newsgroups: comp.std.c Subject: Re: pointers & order of execution Keywords: pointer subtraction, order of execution, realloc Message-ID: <844@cbnewsl.ATT.COM> Date: 19 Jun 89 21:16:06 GMT References: <920@tukki.jyu.fi> <921@tukki.jyu.fi> Reply-To: dfp@cbnewsl.ATT.COM (david.f.prosser) Organization: AT&T Bell Laboratories Lines: 68 In article <921@tukki.jyu.fi> tarvaine@tukki.jyu.fi (Tapani Tarvainen) writes: } }Consider the following code fragment: } } b = (char *) malloc(n); } c = b + x; }... } t = b; } b = (char *) realloc(b, m); }/*1*/ i = b - t; } c += i; } }The idea is that c keeps pointing to the same thing. }Is this guaranteed to work? I think not: }pointer subtraction assumes the pointers point to }the same structure, which b and t don't (unless pANS }says something about realloc in this context?). }And indeed, it may fail with Turbo C and probably any 80x86 C with }large data models. (The problem came up when porting Gnu grep to }ms-dos. See article <920@tukki.jyu.fi> in gnu.utils.bug for details.) } Any use of the value of t after the realloc call causes undefined behavior. Section 4.10.3 of the pANS: The value of a pointer that refers to freed space is indeterminate. And the definition of undefined behavior (section 1.6): ... behavior, upon use ... of indeterminately-valued objects ... The point is that the only portable way of doing the above is to calculate the offset of c from b prior to the realloc. } }Then how about this: } }/*2*/ c = b + (c - t); } }Is this guaranteed to work, or is the compiler free to rearrange it as } } c = (b - t) + c; "c - t" is undefined already. Thus the compiler is free to do anything with this expression. Assuming that it were valid, the rearrangement is not permitted if such were to make it invalid. The translation of the C code must behave as if the abstract machine were actually to execute the code as you wrote it. } }even though b - t is illegal (and fails)? } }I know it can be done safely like this: } } i = c - t; } c = b + i; } }which is what I did, but I'd like to know what pANS says about /*2*/. Only if the realloc comes between the first and the second statement. } }-- }Tapani Tarvainen BitNet: tarvainen@finjyu }Internet: tarvainen@jylk.jyu.fi -- OR -- tarvaine@tukki.jyu.fi Dave Prosser ...not an official X3J11 answer...