On 2017-10-17 10:56, Stefan Ram wrote:
> In several cases of UB, one also could imagine a
> hypothetical language, where the behavior would be merely
> implementation specified.
>
> For example, the division by 0 is undefined behavior, but it
> could as well have been defined to be implementation
> specified.
>
> What are the reasons one sometimes prefers undefined
> behavior to implementation-specified behavior?
Whenever the behavior is unspecified, the standard is supposed to, at
least implicitly, provide a set of different possible behaviors to
choose from. The main reason for preferring undefined behaviour is when
the range of possible behaviors gets too big and complicated to describe
correctly.
Example: overwriting the end of an array. On most systems, there's three
main possibilities. Such overwrites might end up writing to protected
memory, causing your program to abort(). That's not particularly
problematic to describe. An unlikely possibility is that it will simply
be a no-op, also easy to describe. However, if memory protection is not
triggered, such attempts will generally cause an arbitrary piece of
memory to be filled in with a representation of the value you provided.
That piece of memory might or might not be currently in use by some
other part of your program, or by some other program. However, that
can't be used as the description of the behavior. That description must
be in terms of what actually happens as a result of that write. What
will happen depends upon how that piece of memory is being used. For
instance, it might contain the code address that the current function
will jump to when it exits, in which case the function will jump to a
location that depends upon what you wrote to that piece of memory. Or it
might contain one of the other variables in your program, causing that
variable to unexpectedly change value. Or it might contain errno, or
argv[0]. Listing all of the possible consequences of writing to an
arbitrary location in memory is simply impossible. The easiest thing
that covers all of those possibilities is "undefined behavior".