读取未初始化对象的值会产生未定义的行为
Is reading values of unitialized object yields Undefined Behavior
最简单的例子:
int a;
printf("%d\n", a); //Is this Undefined or Unspecified behavior?
N2346/6.3.2.1p2
:
If the lvalue designates an object of automatic storage duration that
could have been declared with the register storage class (never had
its address taken), and that object is uninitialized (not declared
with an initializer and no assignment to it has been performed prior
to use), the behavior is undefined.
但是N2346/6.7.9p10
:
If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate.
因此我们可以得出结论,该对象被初始化为某个不确定值。 不确定值在
处明确定义
N2346/3.19.2p1
:
indeterminate value
either an unspecified value or a trap representation
因为 int
的表示从来都不是陷阱并且应用 N2346/3.4.4p1
unspecified behavior
behavior, that results from the use of an unspecified value, or other
behavior upon which this document provides two
我们知道程序有未指定的行为。
这个推理哪里不对?
Where does this reasoning fail?
这里有一个失败
Since the representation of int
is never a trap
int
可以有陷阱表示。
唯一不能有陷阱表示的类型是 unsigned char
但是标准中也有这部分描述未定义的行为(来自草案 n1570):
J.2 Undefined behavior
...
An lvalue designating an object of automatic storage duration that could have been
declared with the register storage class is used in a context that requires the value
of the designated object, but the object is uninitialized. (6.3.2.1).
最简单的例子:
int a;
printf("%d\n", a); //Is this Undefined or Unspecified behavior?
N2346/6.3.2.1p2
:
If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
但是N2346/6.7.9p10
:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
因此我们可以得出结论,该对象被初始化为某个不确定值。 不确定值在
处明确定义N2346/3.19.2p1
:
indeterminate value
either an unspecified value or a trap representation
因为 int
的表示从来都不是陷阱并且应用 N2346/3.4.4p1
unspecified behavior
behavior, that results from the use of an unspecified value, or other behavior upon which this document provides two
我们知道程序有未指定的行为。
这个推理哪里不对?
Where does this reasoning fail?
这里有一个失败
Since the representation of
int
is never a trap
int
可以有陷阱表示。
唯一不能有陷阱表示的类型是 unsigned char
但是标准中也有这部分描述未定义的行为(来自草案 n1570):
J.2 Undefined behavior
...
An lvalue designating an object of automatic storage duration that could have been declared with the register storage class is used in a context that requires the value of the designated object, but the object is uninitialized. (6.3.2.1).