我对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/22262020/