gpt4 book ai didi

c - 为什么两个相同的指针与 -O1 比较不相等?

转载 作者:行者123 更新时间:2023-12-04 11:02:59 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Can an equality comparison of unrelated pointers evaluate to true?

(4 个回答)


去年关闭。



#include <stdio.h>

int main(void)
{
int a, b;
int *p = &a;

#ifdef __clang__
int *q = &b + 1;
#elif __GNUC__
int *q = &b - 1;
#endif

printf("%p %p %d\n", (void *)p, (void *)q, p == q);
}

C11 § 6.5.9\6 说

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.



我用四种不同的方式对其进行了测试:
  • Clang 9.0.1 与 -01选项;
  • Clang 9.0.1 没有任何选项;
  • GCC 9.2.0 与 -01选项;
  • GCC 9.2.9 没有任何选项。

  • 结果如下:
    $ ./prog_clang
    0x7ffebf0a65d4 0x7ffebf0a65d4 1
    $ ./prog_clang_01
    0x7ffd9931b9bc 0x7ffd9931b9bc 1
    $ ./prog_gcc
    0x7ffea055a980 0x7ffea055a980 1
    $ ./prog_gcc_01
    0x7fffd5fa5490 0x7fffd5fa5490 0

    在这种情况下,正确的行为是什么?

    最佳答案

    What is the correct behavior in this case?



    空无一人。比较指向或结束后的指针 两个完全不相关的对象 是未定义的行为。

    footnote 109 of the C11 standard (粗体是我的):

    Two objects may be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated. If prior invalid pointer operations (such as accesses outside array bounds) produced undefined behavior, subsequent comparisons also produce undefined behavior.

    关于c - 为什么两个相同的指针与 -O1 比较不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59777985/

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