问题
According to C99 J.2, the behavior is undefined when:
The value of an object with automatic storage duration is used while it is indeterminate
What about all the other cases where an object has an indeterminate value? Do we also always invoke UB if we use them? Or do we invoke UB only when they contain a trap representation?
Examples include:
- the value of an object allocated using
malloc
(7.20.3.3p2) - [storing in non-automatic storage] a
FILE*
after callingfclose
on it (7.19.3p4) - [storing in non-automatic storage] a pointer after calling
free
on it (6.2.4p2)
...and so on.
I've used C99 for my references, but feel free to refer to C99 or C11 in your answer.
回答1:
I am using C11 revision here:
The definitions from the standard are:
indeterminate value
either an unspecified value or a trap representation
trap representation
an object representation that need not represent a value of the object type
unspecified value
Unspecified valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance
An unspecified value is a valid value of the relevant type and as such it does not cause undefined behaviour. Using a trap representation will.
But why this wording exists in the standard is that the excerpt enables compilers to issue diagnostics, or reject programs that use the value of uninitialized local variables yet still stay standard-compliant; because there are types of which it is said that they cannot contain trap representations in memory, so they'd always be having unspecified value there in their indeterminate state. This applies to for example unsigned char
. And since using an unspecified value does not have undefined behaviour then the standard does not allow one to reject such a program.
Additionally, say an unsigned char
normally does not have a trap representation... except, IIRC there are computer architectures where a register can be set to "uninitialized", and reading from a register in such an architecture will trigger a fault. Thus even if an unsigned char
does not really have trap representations in memory, on this architecture it will with cause a hardware fault with 100 % probability, if it is of automatic storage duration and compiler decides to store it in a register and it is still uninitialized at the time of the call.
来源:https://stackoverflow.com/questions/37204530/is-using-any-indeterminate-value-undefined-or-just-those-stored-in-objects-with