gpt4 book ai didi

c - 来自未初始化变量的 memcpy 是未定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 16:27:05 24 4
gpt4 key购买 nike

是否使用未初始化的变量作为 memcpy C 中未定义行为的 src

void foo(int *to)
{
int from;
memcpy(to, &from, sizeof(from));
}

最佳答案

C 委员会提出了对 defect report 451: instability of uninitialized automatic variables 的回应是:

The answer to question 3 is that library functions will exhibit undefined behavior when used on indeterminate values.

缺陷中的问题已寻求 memcpy 和 fwrite 的豁免,如果确实如此的话:

[...] The fact that one wants to be able to copy uninitialized padding bytes in structs using memcpy without undefined behavior is the reason that using the value of an uninitialized object is not undefined behavior. This seems to suggest that an fwrite of a struct with uninitialized padding bytes should not exhibit undefined behavior.

提议响应的这一部分似乎是针对未初始化填充的问题:

The committee also notes that padding bytes within structures are possibly a distinct form of "wobbly" representation.

我们可以看到表格defect report 338: C99 seems to exclude indeterminate value from being an uninitialized register这与过去的预期有些不同。它说:

[...] I believe the intent of excluding type unsigned char from having trap representations was to allow it to be used to copy (via memcpy) arbitrary memory, in the case that memory might contain trap representations for some types.[...]

博文Reading indeterminate contents might as well be undefined很好地涵盖了在 C 语言中读取不确定值的演变,并让我对上面提到的变化有了更多的了解。

值得注意的是,这与 C++ 中的 reading an indeterminate value from a narrow unsigned char is not undefined behavior 不同。和 defect report 240注意这个区别:

The C committee is dealing with a similar issue in their DR338. According to this analysis, they plan to take almost the opposite approach to the one described above by augmenting the description of their version of the lvalue-to-rvalue conversion. The CWG did not consider that access to an unsigned char might still trap if it is allocated in a register and needs to reevaluate the proposed resolution in that light. See also issue 129.

关于c - 来自未初始化变量的 memcpy 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33393569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com