C++ - 以下代码会导致未定义的行为吗?

标签 c++ undefined-behavior

<分区>

看看下面的例子:

#include <iostream>
#include <string.h>

void Func1(int x)
{
    std::cout << "I'm function 1: " << x << std::endl;
}

void Func2(int x, const char* str)
{
    std::cout << "I'm function 2: (this is arg1: " << x << " - args2: " << str << ")" << std::endl;
}

uintptr_t GetProcAddress(const char* _str)
{
    if (strcmp(_str, "func1") == 0)
    {
        return reinterpret_cast<uintptr_t>(Func1);
    }
    else
    {
        return reinterpret_cast<uintptr_t>(Func2);
    }
}

int main()
{
    typedef void(*PROCADDR)(int, const char*);
    PROCADDR ext_addr = nullptr;
    ext_addr = (PROCADDR)GetProcAddress((const char*)"func1");

    //call the function
    ext_addr(10, "arg");


    std::cin.get();
    return 0;
} 

我们基本上是使用 2 个参数调用 Func1,并且可以切换为使用相同的参数调用 Func2,一切都按预期进行。

当然,两个参数的地址总是被压入堆栈,即使函数本身从未使用过第二个参数。

现在我明白上面的代码不应该在生产代码中使用,但我的主要问题是,上面的代码会导致 UB 还是代码总是这样?

最好的问候 xx

最佳答案

是的,这是未定义的行为。来自 [expr.reinterpret.cast]:

A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined.

关于C++ - 以下代码会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661791/

相关文章:

c++ - 为什么(如果是这样的话)标准说用 memcpy 复制未初始化的内存是 UB?

c++ - 需要 C 和 C++ 中的未定义行为吗?

c++ - 无权访问模板模板参数

c++ - Debug模式和 Release模式的时间比较(Visual Studio 2008)

c - 快速排序示例(K&R C 书)中的错误?

c - : c = (b=a+2) - (a=1) ; 的未定义行为

c++ - 安全的 reinterpret_cast 与 sockaddr?

c++ - 多级嵌套模板。我如何让它工作?

python - 为 32 位、64 位和 128 位生成交错位模式(莫顿 key )

c++ - 如何在 VSCode C++ 扩展中启用 C++17 支持