use*_*248 2 c memory-alignment undefined-behavior unions language-lawyer
在 C 中,如果我尝试通过未对齐的指针访问类型,则可能会发生不好的事情:
int x[2]; // Assuming CHAR_BIT == 8 && sizeof(int) == 4
*(int *)((char *)x+1) = 10; /* Undefined behavior due to unaligned pointer dereference
even though there are no out of bounds accesses */
Run Code Online (Sandbox Code Playgroud)
但是,如果相关类型是 a但我只访问不具有对齐要求union的成员,该怎么办?union
union X {
int i;
char c[4];
} x[2];
((union X *)((char *)x+1))->i = 10; /* I am guessing this is still undefined behavior
because accessing an unaligned int through a union does not make a difference as far as I know */
Run Code Online (Sandbox Code Playgroud)
但是下面的代码会调用未定义的行为吗?
((union X *)((char *)x+1))->c[0] = 10;
Run Code Online (Sandbox Code Playgroud)
我很怀疑,因为一方面我union通过运算符取消引用指针,并且由于该字段->而具有对齐要求,但另一方面,我没有触及该字段。那么这会导致任何未对齐的指针访问冲突吗?unionintint
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |