memcpy 的 src 和 dest 参数是否允许重叠?

Is it allowed for src and dest arguments of memcpy to overlap?

我需要移动字节缓冲区的内容。当然,我开始写 memcpy,但后来意识到它可能有 restrict 源和目标说明符。我的实现(MSVC 2013)似乎没有。 Cppreference 列出了两个 memcpy 版本,有和没有 restrict,但我不明白 - 我不认为这些是重载,我不清楚编译器如何正确确定要重载的版本挑选。 另一方面,memcpy 函数可以在运行时分析地址和 count 参数以确定地址范围是否重叠。

那么,是否允许使用重叠参数调用 memcpy?如果没有,有什么方法可以比普通的 for?

更好地执行此操作

没有it is not, you should use memmove.

来自memcpy(3)

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap.

来自 memmove(3):

The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest.

C99标准中加入了restrict关键字,这就是cppreference列出两个版本的原因(如果仔细看右边,可以看到until C99since C99).

memcpy 中的内存不能重叠,否则您将面临未定义行为的风险。

改用 memmove。