Undefined behaviour in C [was Re: The Cost of Dynamism]

Steven D'Aprano steve at pearwood.info
Sun Mar 27 03:40:35 EDT 2016


On Sun, 27 Mar 2016 05:13 pm, Paul Rubin wrote:

> Steven D'Aprano <steve at pearwood.info> writes:
>> For example, would you consider that this isolated C code is
>> "meaningless"?
>> int i = n + 1;
> 
> It's meaningful as long as n is in a certain range of values so there's
> no overflow.
> 
>> But according to the standard, it's "meaningless", since it might
>> overflow, and signed int overflow is Undefined Behaviour.
> 
> No it's not meaningless if it "might" overflow, it's meaningless if it
> -does- overflow, 

No! That's exactly wrong!

Paul, thank you for inadvertently proving the point I am trying to get
across. People, even experienced C coders, simply don't understand what the
C standard says and what C compilers can and will do.

If the C compiler cannot prove that n is strictly less than MAXINT (or is
that spelled INT_MAX?), the *entire program* (or at least the bits
reachable from this line, in both directions) is Undefined, and the
compiler has no obligations at all.

You probably don't believe me because this sounds crazy, something that no
sane person would design a programming language to behave. Well, yeah,
exactly. It does allow C a lot of powerful optimizations, but only at the
cost of making it impossible to reason about the behaviour of code that is
Undefined. No real compiler is going to intentionally erase your hard disk,
but in non-toy code, it can introduce serious bugs even though you
explicitly wrote code to avoid the buggy case.

But don't believe me. What do I know about C, I don't even know whether to
spell the biggest int MAXINT or INT_MAX or MAX_INT. Instead, believe these
guys:

http://blog.regehr.org/archives/213
http://blog.regehr.org/archives/226
http://blog.regehr.org/archives/232

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html

https://blogs.msdn.microsoft.com/oldnewthing/20140627-00/?p=633/

https://randomascii.wordpress.com/2014/05/19/undefined-behavior-can-format-your-drive/


I've emphasised all the bad things that undefined behaviour causes, but the
above (written by C programmers who presumably like C) are much more
even-handed, describing the good things that compilers can get out of this.




-- 
Steven




More information about the Python-list mailing list