我想看看是否restrict会阻止memcpy访问重叠内存。
该memcpy函数将n个字节从内存区域src直接复制到内存区域dest 。内存区域不应重叠。memmove使用缓冲区,因此没有重叠内存的风险。
该restrict限定词表示,对指针的寿命,只有指针本身或直接从一个值(例如pointer + n)将具有访问该对象的数据。如果没有遵循意图声明并且对象被一个独立的指针访问,这将导致未定义的行为。
#include <stdio.h>
#include <string.h>
#define SIZE 30
int main ()
{
char *restrict itself;
itself = malloc(SIZE);
strcpy(itself, "Does restrict stop undefined behavior?");
printf("%d\n", &itself);
memcpy(itself, itself, SIZE);
puts(itself);
printf("%d\n", &itself);
memcpy(itself-14, itself, SIZE); //intentionally trying to access restricted memory
puts(itself);
printf("%d\n", &itself);
return (0);
}
Run Code Online (Sandbox Code Playgroud)
输出 ()
自身地址:12345
限制是否停止未定义的行为?
自身地址:12345
停止未定义的 bop 未定义行为?
自身地址:12345
是否 …