3 ms·
In the actual code *(p+1) is only ever accessed if it has been verified to be the same address as q[0], which is an object which we know exists and we have full
by serbuvlad 2y ago
In the actual code *(p+1) is only ever accessed if it has been verified to be the same address as q[0], which is an object which we know exists and we have full access to.
The problem is that pointers of the same type to the same address but originating from pointer arithmetic on the pointers obtained by dereferencing different objects have different semantics.
In other words, the following is not semantically a NOP.
char *p = /*some valid pointer*/;
{
char x;
char *q = &x;
while ((uintptr_t) q != (uintptr_t) p)
q++;
p = q;
}
I believe this goes against the principle of least astonishment (I find it quite astonishing, personally). I believe, even if the standard not does not guarantee the expected behavior, that implementations should still guarantee it. And they can do the optimizations they want in other ways, as I have outlined.
- Groxx 2y agoWhile I generally agree and I much prefer my langs with minimal undefined behavior, this gets solidly into Hyrum's Law territory, and it means practically every significant optimization could break something therefore it cannot be done. C just doesn't have rich enough semantics to allow much else. You can find some languages that try to adhere to that, but C is extremely clearly not part of that group. It never has been, and it never will be.
- imtringued 2y agoThe problem with C is not necessarily the idea of undefined behavior. It's the culture around undefined behavior. There is no culture of avoiding UB in a programming language community that glorifies UB as necessary. That's the paradox. It's like you're supposed to cross an enemies' minefield, with the enemy laying ever more mines in your path and yet you're supposed to walk through the minefield and hope for the best. You'd have thought that C programmers have the best tools and techniques to avoid UB by now, so that UB would be a non-issue, a relic of the past that people remember suffering from in the 90s.