Skip to content

UB25⚓︎

author: Xiangzhi Liu.

Definition⚓︎

A pointer is used to call a function whose type is not compatible with the referenced type(6.3.2.3).

Description⚓︎

当函数指针被强制转换成指向与其引用类型不兼容的函数类型并被用于函数调用时,结果是未定义的

Code⚓︎

UB25.c
#include <stdio.h>
int f(int x)
{
    return x + 1;
}

int main() {
    int (*pf)(int) = f;
    double a = (*(double(*)(int))pf)(1);
    printf("%lf\n", a);
    return 0;
}

Configurations⚓︎

gcc version 4.9.2

Target: x86_64-w64-mingw32

MSVC _MSC_VER = 1928

Target: x86_64

Behaviors⚓︎

通过编译无警报 输出:1250137480162850900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

通过编译无警报 输出:-nan(ind)

Advice⚓︎

对函数指针进行类型转换时应保证转换前后的引用(函数)类型的参数和返回值的类型是兼容的。更进一步,函数指针在大部分情况下不需要进行类型转换,避免对函数指针进行类型转换可以避免该问题。