UB24⚓︎
author: Xiangzhi Liu.
Definition⚓︎
Conversion between two pointer types produces a result that is incorrectly aligned (6.3.2.3).
Description⚓︎
将一种指针类型(T)转换为另一种指针类型(P)时,该指针对象的值不满足 P 类型的对齐要求,那么结果是未定义的。
Code⚓︎
UB24.c
#include <stdio.h>
int main() {
char a[16] = {1,2,3,4,5,6,7,8};
int* p = (int*)a;
int* q = (int*)(a + 1); // Either this line or previous line produces a UB
printf("0x%04X, 0x%04X\n", *p, *q);
return 0;
}
Configurations⚓︎
gcc version 4.9.2
Target: x86_64-w64-mingw32
MSVC _MSC_VER = 1928
Target: x86_64
Behaviors⚓︎
通过编译无警报 输出:0x4030201, 0x5040302
通过编译无警报 输出:0x4030201, 0x5040302
Advice⚓︎
保证转换前指针对象的值符合转换后类型的对齐要求。