c - 是否保证执行 memcpy(0,0,0) 是安全的?

标签 c memcpy language-lawyer null-pointer

我对C标准不是很精通,所以请多多包涵。

我想知道根据标准是否可以保证 memcpy(0,0,0) 是安全的。

我能找到的唯一限制是,如果内存区域重叠,则行为未定义...

但是我们可以认为内存区域在这里重叠吗?

最佳答案

我有一个 C 标准的草案版本 (ISO/IEC 9899:1999),它有一些关于那个调用的有趣的事情要说。对于初学者,它提到 (§7.21.1/2) 关于 memcpy

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.

此处指示的引用指向:

If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.

所以它看起来像根据 C 规范,调用

memcpy(0, 0, 0)

导致未定义的行为,因为空指针被认为是“无效值”。

就是说,如果您这样做的话,如果 memcpy 的任何实际实现失败,我会感到非常惊讶,因为如果您说要复制,我能想到的大多数直观实现根本不会做任何事情零字节。

关于c - 是否保证执行 memcpy(0,0,0) 是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5243012/

相关文章:

c - 避免多类型结构的 memset

c - 从结构到数组的不完整复制

c - memcpy 问题(内部结构)

c++ - memcpy/memmove 到 union 成员,这是否设置了 'active' 成员?

c++ - 我们可以访问不存在的类类型对象的成员吗?

c++ - 在查找::之前的名称时,函数模板的名称是否应该可见?

ios - 尝试了解iOS开发中的AVAudioPlayer

c - 尝试将字符附加到字符数组

java - JNA 通过引用传递结构帮助

c - 在 C 中读取 1 GB 二进制文件花费的时间太长