5 ms·
My opinion on that, is that such code MUST NOT be optimized away. Instead it should be a compile error.
by mjevans 8y ago
My opinion on that, is that such code MUST NOT be optimized away. Instead it should be a compile error.
- raphlinus 8y agoYou might wish for that, but the ship has sailed. Undefined behavior means that the implementation can do whatever it can. That said, I do expect tools, both sanitizers and static analyzers to improve to detect more of these kinds of cases.
- umanwizard 8y agoWell, not exactly. There are things that are UB according to the standard but that particular compilers give an option to make defined: see `-fwrapv`, for example.
- AnimalMuppet 8y agoThere have been static analyzers that will detect this for years. They report "check for null after use" or some such.
- lmm 8y agoThe original intention of standardization was that compilers would gradually reach consensus on what the behaviour in certain cases should be, and once that happened the standard would be updated to standardize that behaivour. Compilers are allowed - indeed encouraged - to provide additional guarantees beyond the minimum defined in the standard (indeed part of the point of UB is that a compiler is allowed to specify what the behaviour is in that case).
- umanwizard 8y agoThe problem, as far as I understand it (though I’m a layman), is that by the time the dead code optimization pass runs, the code has been transformed so much that there’s no obvious way for the compiler to tell the difference between “obvious programmer-intended null check that we shouldn’t optimize out” and “spurious dead code introduced by macro expansion” or (in C++) “by template instantiation”.
- mjevans 8y agoCouldn't user defined branches be tagged by such a compiler and if a tagged branch is eliminated the error generated with a reference to the tagged line in question?
- umanwizard 8y agoThat is a good idea and I’ll admit that I’m not sure why it isn’t implemented.
- deleted 8y ago[deleted]
- int_19h 8y agoWhy should it be a compile error? The pointer may be null, but is not guaranteed to be. If you mean that C++ should require a null check before dereferencing any pointer that is not guaranteed to be non-null, then that would break most existing C++ code out there, so it's a non-starter.
- leetcrew 8y agoin the particular situation they're talking about, you have a pointer to a struct, which you dereference by accessing one of its fields. the null check happens after the dereference, almost certainly a mistake.