首页 > 解决方案 > 将堆存储从 const 转换为非常量会调用未定义的行为吗?

问题描述

标准 说:

(6.7.3) 如果尝试通过使用具有非 const 限定类型的左值来修改使用 const 限定类型定义的对象,则行为未定义。

在未定义的行为部分:

尝试通过使用具有非 const 限定类型的左值来修改使用 const 限定类型定义的对象 (6.7.3)

malloc的返回值是一块未初始化的存储。在该存储中没有构建任何对象。

也就是说,下面的代码合法吗?

#include
#include

typedef struct {
    unsigned char h;
    const unsigned int v;
} liber_primus;

int main(int argc, const char **argv)
{
    unsigned int lykilord;

    if (!(argc - 1))
        return 0;

    liber_primus *runaljod = malloc(sizeof (*runaljod));

    if (!runaljod)
        abort();

    runaljod->h = *(unsigned char *)argv[1];
    *(unsigned int *)&runaljod->v = 3307U;

    lykilord = runaljod->h * runaljod->v;

    free(runaljod);

    return lykilord;
}

标签: cmallocconstantslanguage-lawyerundefined-behavior

解决方案


推荐阅读