2 ms·
> if 'p' was dereferenced before the check Oops, I misread! Yes, you've got undefined behaviour (i.e. a serious bug in your code), and as far as the compiler
by MaxBarraclough 8y ago
> if 'p' was dereferenced before the check
Oops, I misread!
Yes, you've got undefined behaviour (i.e. a serious bug in your code), and as far as the compiler is concerned, anything goes.
As the old joke goes, the philosophy of the C language is that the programmer is always right, even when they are wrong. i.e. that it's your job to ensure there's no UB in your source code.
The 'C way' is not to have the language shield you from your mistakes. You can't have that without losing C's advantages. Fortunately, tools exist to help detect undefined behaviour.
It's a pity that runtime detection of easily-detected UB hasn't been an option in C compilers since the beginning. For dev/debug builds, that's almost certainly what you want.
- fao_ 8y ago> i.e. that it's your job to ensure there's no UB in your source code. Have you seen the UB list though? It seems to me that almost all programs fall under some kind of UB. It would be nice to have the compiler produce warnings where it would otherwise optimize based on that UB.
- MaxBarraclough 8y agoUnfortunately it's a theoretical impossibility to detect all instances of UB in a static-analysis. Rice's theorem strikes again. These days we have pretty good static analysis tools, and tools like UBSan which can insert certain checks at runtime. Not perfect though. I believe it's possible to approach it from the other side though: use MISRA C, a terribly strict C programming ruleset, which I believe can be mechanically verified, and which avoids any possible UB. (This is an 'overly strict' approach, as it forbids doing certain perfectly legal things.)
- AstralStorm 8y ago1. No they don't. 2. The easiest ones to hit by accident are integer overflow ones followed by trapping floating point math. 3. Pointer aliasing is hard to hit if you're not baiting it. 4. Threading requires Data Race Free code. No language known validates this enough. 5. Unchecked pointer dereference and lifetime problems can be avoided especially in C++. It is a subset of missing input validation which again is not enforced in most programming languages. 6. Object slicing rarely comes into play on its own. 7. Format string mess also easy to avoid, s are weirdness caused by longjmp, signals and other ways of messing with the stack. There are 193 UB cases in C99 and most of them are redundant and group able. Bunch of them can be called "programmer brain is out to lunch". The list is bigger slightly in C20.