gpt4 book ai didi

c - 在标准 C 中从头开始实现 memcpy 在技术上是不可能的吗?

转载 作者:太空狗 更新时间:2023-10-29 16:39:07 25 4
gpt4 key购买 nike

朱浩 writes :

In the latest C spec it is impossible to write a "legal" implementation of malloc or memcpy.

这样对吗?我的印象是,在过去,该标准的意图(至少)是这样的事情会起作用:

void * memcpy(void * restrict destination, const void * restrict source, size_t nbytes)
{
size_t i;
unsigned char *dst = (unsigned char *) destination;
const unsigned char *src = (const unsigned char *) source;

for (i = 0; i < nbytes; i++)
dst[i] = src[i];
return destination;
}

这里违反了最新的C标准中的哪些规则?或者,此代码未正确实现 memcpy 规范的哪一部分?

最佳答案

对于 malloc 函数,第 6.5 节第 6 段明确指出不可能编写一致且可移植的 C 实现:

The effective type of an object for an access to its stored value is the declared type of the object, if any(87)...

(非规范性)注释 87 说:

Allocated objects have no declared type.

声明一个没有声明类型的对象的唯一方法是......通过返回这样一个对象所需的分配函数!因此在分配函数内部,您必须有 一些东西 标准不允许设置没有声明类型的内存区域。

在常见的实现中,标准库 malloc 和 free 确实是用 C 实现的,但系统知道这一点,并假定在 malloc 中提供的字符数组只是没有声明类型。句号。

但是同段的剩余部分说明写一个memcpy实现没有真正的问题(强调我的):

... If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value. If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

假设您将对象复制为字符类型的数组,这是根据严格的别名规则允许的特殊访问,实现 memcpy 没有问题,并且您的代码是可能且有效的实现。

恕我直言,Howard Chu 的咆哮是关于那个旧的好 memcpy 用法,它不再有效(假设 sizeof(float) == sizeof(int)):

float f = 1.0;
int i;
memcpy(&i, &f, sizeof(int)); // valid: copy at byte level, but the value of i is undefined
print("Repr of %f is %x\n", i, i); // UB: i cannot be accessed as a float

关于c - 在标准 C 中从头开始实现 memcpy 在技术上是不可能的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54336811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com