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

标签 c language-lawyer undefined-behavior memcpy

是否使用未初始化的变量作为 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/

相关文章:

c++ - 没有 delete() 的 new() 是未定义行为还是仅仅是内存泄漏?

c - scanf() 在 ENTER 后不起作用

c - 复杂函数定义中的参数范围

c - 在 C 中获取临时(复合文字)参数的地址

c++ - C++ 重载解析规则中的缺陷?

c - 为什么当 N 越界时 &a[N] 不调用 UB?

c++ - 是否使用无效指针未定义行为初始化指针声明符?

C指针: Explain the program concept

c - 函数声明与原型(prototype)的替代 (K&R) C 语法

c - Windows 命令提示符如何处理连续的 CTRL + C (SIGINT) 信号?