C语言中的undefined behavior系列(3) -- trap representation
时间:2010-08-31 来源:嗷嗷
文章的传送门: C语言中的undefined behavior/unspecified behavior - 序
嗷嗷的话: 本文里只要是大段大段的英文,都来至C99标准。所有的中文注释都是我对标准的理解。在文中使用的编译器是开了C99支持Intel C Compiler 11 for Windows.
— A trap representation isread by an lvalue expression that does not have character type(6.2.6.1).
— A trap representation isproduced by a side effect that modifies any part of the object using an lvalueexpression that does not have character type (6.2.6.1).
什么是traprepresentation?简单来说trap representation就是不合理,没有意义,无效的值。对于这样的值的读写会造成硬件的trap exception.
举个例子,比如说某种硬件使用32bits来表示一个有符号整数,最高位为符号位,0表示正数,1表示负数。并且定义0为0x00000000,那么0x80000000就是一个trap representation。
另外一个例子是,某硬件使用30bits来表示一个整数,额外的2bits作为校验位,这样也存在trap representation。
所以,读一个traprepresentation或者部分写一个trap representation是一个undefined behavior。
[注1]一个automatic variable可以被初始化为一个traprepresentation,比如说被分配在站上的局部变量,其内存中本来有的值可能就是一个trap representation。但这样的初始化并不是一个undefined behavior,除非不对他正确赋值就是用这个值,才是一个trap representation的undefined behavior
[注2] unspecifiedvalues不等同于trap representation. 比如说padding value in structure就是一个unspecifiedvalue但是不是trap representation,比如说,两个structure相互赋值,虽然有padding value,但是这不是trap representation
[注3] value --precise meaning of the contents of an object when interpreted as having aspecific type
implementation-defined value -- unspecified value where eachimplementation documents how the choice is made
indeterminate value -- either an unspecified value or a traprepresentation
unspecified value -- valid value of the relevant type where thisInternational Standard imposes no requirements on which value is chosen in anyinstance. An unspecified value cannot be a trap representation