3 ms·
> One of those transformation detects that we are reading uninitialized memory and acts accordingly. This might be pedantic but variables do not have to corres
by muldvarp 3y ago
> One of those transformation detects that we are reading uninitialized memory and acts accordingly.
This might be pedantic but variables do not have to correspond to memory locations. The compiler could decide to keep the variable in a register or the compiler might realize that the variable never changes and apply constant folding eliminating it entirely. Assuming that variables correspond to memory locations (or really any assumptions about how code is translated into assembly) is a part of the "portable assembler"-understanding of C that simply doesn't apply to (optimizing) C compilers.
> Given that most of the case where we do it is by mistake, I think that doing anything other than raising an error (or at least a big warning) is not a very reasonable thing to do.
I agree that the compiler should warn if it can prove that a programs behavior is undefined unconditionally. I don't think it's as easy as you make it out to be, but I encourage you to check out the source code of clang and fix this issue if that's possible. That said, in practice undefined behavior is often encountered conditionally (e.g. the behavior of this function is undefined if and only if the first argument is non-null and the second argument is null). Optimizing such programs is trivial (simply assume that undefined behavior cannot happen and optimize accordingly), detecting that the program actually calls that function with invalid parameters on the other hand is _literally_ impossible and even a best-effort approach would be computationally expensive and miss a lot of cases.