Hacker News new | ask | show | jobs
by akvadrako 3545 days ago
Okay, good point - so it's the deferencing step that evokes the clause your mentioned. Apparently, what I learned today, is the cast is fully legal even though it could produce an invalid pointer.

I still wonder if my snippet counts as undefined behavior, since it does dereference an "unknown" void pointer, which may have come from an incompatible object type.

BTW, the latest C1X draft is only at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

1 comments

> I still wonder if my snippet counts as undefined behavior, since it does dereference an "unknown" void pointer, which may have come from an incompatible object type.

It counts as potentially undefined behavior - depends on what you pass in. NULL? UB. Pointer-to-uint64_t? UB. Pointer-to-uint32_t? Perfectly defined behavior! ...well, assuming we use ip[0] = 123; instead of ptr[0] = 123;, which won't compile as I've just noticed.

That said, there are some ways to construct pointers which are in and of themselves undefined behavior for merely constructing the pointer:

http://stackoverflow.com/questions/23683029/is-gccs-option-o...

More samples:

  int a[] = { 1, 2, 3 };
  int* b = a+0; // Perfectly defined/legal/normal
  int* c = a+3; // Perfectly defined/legal/normal, just don't deference it (as it points past the end of the array)
  int* d = a+4; // Undefined behavior.  HAIL SATAN!
  int* e = a-1; // Undefined behavior.  Also apparently potentially caused optimization induced breakage in practice.  HAIL GCC!