LWN.net Logo

would using casts fix the problem?

would using casts fix the problem?

Posted Apr 16, 2008 19:23 UTC (Wed) by roskegg (subscriber, #105)
Parent article: GCC and pointer overflows

So if I cast the pointers to long unsigned ints, would the second test THEN be optimized away?


(Log in to post comments)

would using casts fix the problem?

Posted Apr 16, 2008 19:31 UTC (Wed) by zeekec (subscriber, #2414) [Link]

would using casts fix the problem?

Posted Apr 16, 2008 19:40 UTC (Wed) by mb (subscriber, #50428) [Link]

> So if I cast the pointers to long unsigned ints, would the second test THEN be optimized
away?

Some german news site stated a few days ago that it would not optimize it away then. They
proposed it as a possible workaround.

would using casts fix the problem?

Posted Apr 16, 2008 19:46 UTC (Wed) by MathFox (guest, #6104) [Link]

I recall that one programmer asked me why
int main() {
   char a[10];
   char *aend = a+10;

   printf("%ld\n", (int)aend - (int)a);
}
did print something different from 10 on a Cray vector computer...

would using casts fix the problem?

Posted Apr 16, 2008 19:50 UTC (Wed) by MathFox (guest, #6104) [Link]

Make the printf line printf("%lu\n", (unsigned long)aend - (unsigned long)a);

would using casts fix the problem?

Posted Apr 16, 2008 20:27 UTC (Wed) by jengelh (subscriber, #33263) [Link]

Or better yet don't cast at all. %td for printf can take a ptrdiff_t, which is what such a subtraction should usually yield.

would using casts fix the problem?

Posted Apr 16, 2008 21:29 UTC (Wed) by MathFox (guest, #6104) [Link]

I guess that you missed the point completely. aend-a (no casts needed) should give 10 on any platform. The bit pattern in a pointer is implementation defined and that particular platform had (64-bits IIRC) word-based addresses in a 48 bit address space. The low 48 bits of a character pointer were the address of the word containing the character; the high bits addressed the byte in the word.

Standard conforming programs don't rely on pointer layout.

would using casts fix the problem?

Posted Apr 17, 2008 18:55 UTC (Thu) by hummassa (subscriber, #307) [Link]

yes,
  aend - a
(without cast) _is_ 10 in any platform, but
  (int)aend - (int)a
is _undefined_ behaviour, because the bit pattern when converting from 
pointer to int is implementation-defined.

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds