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

相关文章:

c - 由宏定义的结构体变量大小返回 "this operator is not allowed in a constant expression"

c++ - 为什么 memcpy 到栈上内存比堆上内存快得多?

c - memcpy: unix socket sun_path 起始地址索引

c - `*`(星号)是 C11 中的关键字吗?

c++ - 非局部非内联变量的初始化 : does it take place strictly before the `main()` function call?

C 测试 - Unity 和 CMake 的 undefined reference

c - while(!feof(file)) 读取额外的行

c - Linux 内核模块 - IOCTL 使用返回 ENOTTY

c - 如何在多维数组中添加数组?

c++ - GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?