强制转换和调用函数的参数计数是否指定行为?

Is Casting and Calling a Function's Parameter Count Specified Behaviour?

本文关键字:是否 参数 转换 调用 函数      更新时间:2023-10-16

这个问题具体涉及reinterpret_cast和后续使用nullptr作为第三个参数的函数调用。这是指定的行为吗?

我使用 malloc/free 是因为使用 delete 删除 void 指针是未指定的行为。无论;这个问题也应该考虑非空指针(作为参数)。

#include <cstdlib>
#include <iostream>
void *add2Ints(void *a, void *b)
{
    void *res = malloc(sizeof(int));
    *((int *) res) = *((int *) a) + *((int *) b);
    return res;
}
int main(int argc, char *argv[])
{
    void *x = malloc(sizeof(int));
    void *y = malloc(sizeof(int));
    *((int *) x) = 31;
    *((int *) y) = 16;
    void *(*add2Ints_p)(void*, void*, void*) = reinterpret_cast<void *(*)(void*, void*, void*)>(add2Ints);
    void *z = add2Ints_p(x,y,nullptr);
    std::cout << *((int *) z);
    free(x);
    free(y);
    free(z);
}

使用reinterpret_cast投射的指针的唯一合法做法是将其转换回其原始类型。

所以,在这里我们肯定在 UB 土地上(如果调用约定要求被叫方清理,你肯定会在返回时粉碎堆栈或崩溃)。

相关文章: