相关疑难解决方法(0)

为什么限制限定符仍然允许 memcpy 访问重叠内存?

我想看看是否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

是否 …

c memcpy restrict-qualifier

1
推荐指数
1
解决办法
1417
查看次数

标签 统计

c ×1

memcpy ×1

restrict-qualifier ×1