pointers & order of execution

david.f.prosser dfp at cbnewsl.ATT.COM
Tue Jun 20 07:16:06 AEST 1989


In article <921 at tukki.jyu.fi> tarvaine at 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 at 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 at finjyu
}Internet:  tarvainen at jylk.jyu.fi  -- OR --  tarvaine at tukki.jyu.fi

Dave Prosser	...not an official X3J11 answer...



More information about the Comp.std.c mailing list