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

Steven D'Aprano steve at pearwood.info
Fri Mar 25 22:46:52 EDT 2016


On Sat, 26 Mar 2016 03:57 am, Marko Rauhamaa wrote:

> Steven D'Aprano <steve at pearwood.info>:
> 
>> Undefined behaviour in C is a minefield waiting to blow your program's
>> legs off, because the designers of the language made the explicit
>> choice that they wanted the language to be as fast and efficient as
>> possible, even at the cost of safe, reproducible behaviour.
> 
> Yes, although the same could be true for Python as well.

Is this a philosophical question? Yes, it *could* be true, in some alternate
universe, but it isn't actually true.

Python does not have undefined behaviour in the C sense. Like any language
which doesn't have a formal IEEE standard behind it (and even some that
do), it has implementation-specific behaviour, or under- or unspecified
behaviour. But that is not the same as C Undefined Behaviour. Please read
the links I gave.

Culturally, C compiler writers have a preference for using undefined
behaviour to allow optimizations, even if it means changing the semantics
of your code. The C compiler is allowed to ignore your code, move it around
so that things happen in a different order, or add its own code, even if
that changes the semantics of the code.

Python has nothing even remotely like that. If you shoot yourself in the
foot with Python, you can say it is because you didn't understand what your
code would do, but you can't say it is because Python moved code around to
execute it in an unexpected order, or ignored it.



> For example, you could have this program:
> 
> ===begin poof.py========================================================
> assert 1 < 0
> ===end poof.py==========================================================

The semantics of "assert condition" are equivalent to:


if __debug__:
    if not condition:
        raise AssertionError


so assert is intentionally a no-op when Python runs with debug mode disabled
(the -O command-line switch).


 
> When it is run, you might see this:
> 
> ========================================================================
> $ python3 poof.py
> python3: the VM vanished in a puff of logic while executing 'poof.py'
> ========================================================================

I assume that the "vanished" quip is your editorial. Otherwise, the only way
to get that result would be if you linked the python3 executable to
something other than Python 3.

There are only two behaviours a conforming Python interpreter can do
with "poof.py":

- by default, it must raise AssertionError;

- if run with optimizations switched on (debugging mode turned off), 
  it must do nothing.


Anything else would be a bug in the interpreter or compiler.




-- 
Steven




More information about the Python-list mailing list