"Ancient_Hacker" <gr**@comcast.netwrites:
Serve Laurijssen wrote:
>Consider the following code
char *p1 = malloc(10);
char *p2 = malloc(10);
if (p1 p2)
puts("bigger");
free(p1);
if (p1 p2)
puts("bigger");
is this a case of UB on the second comparison? Since p1 does contain a valid
value even though there's no valid object there anymore.
Several issues:
(1) I doubt if C assigns any meaning to pointer ordering, so why
should you expect p1 p2 to mean anything even if p1 and p2 are still
allocated?
Why speculate?
C certainly does assign a meaning to pointer ordering. If it didn't,
the ">" operator wouldn't be legal for pointer operands.
Relational operators ("<", "<=", ">", ">=") on pointer values are
meaningful only if both point into the same object; otherwise the
behavior is undefined. See C99 6.5.8p5 for details; Google n1124.pdf
for a copy of the standard (plus TC1 and TC2).
(2) After a free(p1) I can't think of anything you can do with p1
other than setting it to another value. Even comparing it for
equality to another pointer sounds really iffy, and probably useless
to boot.
After free(p1), the value of p1 is indeterminate; referring to that
value in any way (potentially) invokes undefined behavior. (I added
the weasel-word "potentially" because of some subtle issues involving
indeterminate values vs. trap representations vs. unspecified values;
there's been a discussion recently in comp.std.c. Bottom line: Don't
do that.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.