Skip to content

UB23⚓︎

author: Xiangzhi Liu.

Definition⚓︎

Conversion of a pointer to an integer type produces a value outside the range that can be represented (6.3.2.3).

Description⚓︎

将指针类型强制转换为整数类型时,如果该整数类型的值范围不足以容纳指针的值,那么行为是未定义的。

Code⚓︎

UB23.c
#include <stdio.h>
int main() {
    int a;
    int* p = &a;
    unsigned char b = (unsigned char)p;  // UB. sizeof(unsigned char) == 1 and for most platform sizeof(int*) > 1
    printf("0x%X, 0x%X\n",(uintptr_t)p,b);
    return 0;
}

Configurations⚓︎

gcc version 4.9.2

Target: x86_64-w64-mingw32

MSVC _MSC_VER = 1928

Target: x86_64

Behaviors⚓︎

通过编译并产生警报 “cast from pointer to integer of different size [-Wpointer-to-int-cast]” 输出:0x62FE10, 0x10

通过编译无警报 输出:0xAFF7E0, 0xE0

Advice⚓︎

如果需要将指针强转为整数,应使用 intptr_tuintptr_t 类型的对象存放指针的值。