是否正在转换并调用函数的参数计数指定行为?

时间:2014-04-03 18:31:08

标签: c++

问题 - 特别是 - 使用nullptr作为第三个参数的reinterpret_cast和后续函数调用。这是指定的行为吗?

我使用malloc / free是因为使用delete删除void指针是未指定的行为。而不管;这个问题也应该考虑非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);
}

1 个答案:

答案 0 :(得分:1)

对于使用reinterpret_cast投射的指针,唯一合法的做法是将其强制转换为原始类型。

所以,我们肯定在UB-land(如果调用约定要求被调用者清理你肯定会粉碎堆栈或者在返回时崩溃)。