4 ms·
> My understanding is that C has undefined behaviour where there is no universally sensible implementation across all architectures. That's somewhat true for t
by dbaupp 8y ago
> My understanding is that C has undefined behaviour where there is no universally sensible implementation across all architectures.
That's somewhat true for things like signed integer overflow, but it's more than that. For instance, if there wasn't UB around pointers being "in bounds", then either there would have to be expensive checking of every pointer dereference ever (both read and write), or other performance drains like values never ending up in registers (both literally and conceptually) for extended periods, they'd have to be loaded from memory every time they're used, effectively treated as `volatile`. (And, this inhibits other optimizations like breaking up structs via SROA.)
For instance,
int f(int *p) {
int x = 0;
*p = 10;
if (x != 0) { ... }
}
The compiler can't optimize out the branch unless it can assume (or dynamically ensure) that the dereference of the pointer p won't point to an unrelated object (x). Arbitrary transformations on pointers (including constructing them directly from integers, and one might guess the stack address of x) are "only" undefined behaviour in C, not prohibited statically.
- MaxBarraclough 8y ago> Arbitrary transformations on pointers (including constructing them directly from integers, and one might guess the stack address of x) are "only" undefined behaviour in C, not prohibited statically. Sure, that's what it means to have full pointer arithmetic. It's very much an aim away from face feature of the language.
- dbaupp 8y agoYes, that is exactly my point. It's a dangerous feature of the language, or, said another way, has a lot of potential for undefined behaviour. If one is trying to reword the standard to control undefined behaviour, this is one feature that needs to be considered.