gpt4 book ai didi

c - 在 memmove 中使用 __np_anyptrlt?

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:35 25 4
gpt4 key购买 nike

从这个链接: http://clc-wiki.net/wiki/memmove

#include <stddef.h> /* for size_t */
void *memmove(void *dest, const void *src, size_t n)
{
unsigned char *pd = dest;
const unsigned char *ps = src;
if (__np_anyptrlt(ps, pd))
for (pd += n, ps += n; n--;)
*--pd = *--ps;
else
while(n--)
*pd++ = *ps++;
return dest;
}

是利用__np_anyptrlt多余的?为什么不直接使用 if (ps < pd)

最佳答案

您链接的页面上的注释对此进行了解释:

__np_anyptrlt(p1, p2):

A macro or function such that, for any two pointers p1 and p2, __np_anyptrlt(p1,p2) evaluates to:

  • non-zero if p1 and p2 point within the same object and p1 is lessthan p2
  • zero if p1 and p2 point within the same object and p1 is greater than p2
  • an unspecified integer value if the pointers don't point within the same object or if they compare equal.

A naive implementation is ((p1) < (p2)), but according to the Standard, 6.5.9 (N1124 numbering), this results in undefined behavior when p1 and p2 do not point within (or one member past the end of) a single array object. This naive implementation should only be used then by implementors who can ensure that the behaviour is always reasonable in those cases. The actual end value of the expression doesn't matter in those cases though because for distinct objects it's impossible to corrupt memory no matter which direction memmove iterates in.

所以,只有使用 ps < pd 才是安全的如果您的平台保证指向不同数组的指针之间的比较行为正常。该标准表示此类比较是未定义的,因此无用的编译器可能会创建执行任何操作的代码(例如崩溃、损坏数据或让恶魔从你的 Nose 里飞出来)。

大多数编译器可能会做一些可接受的事情,但您需要查阅特定编译器的文档才能确定。

关于c - 在 memmove 中使用 __np_anyptrlt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062776/

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