gpt4 book ai didi

C++ 数组超出范围访问计算指针有效?

转载 作者:太空狗 更新时间:2023-10-29 22:56:21 24 4
gpt4 key购买 nike

下面的代码保证有效吗?

int* arr = new int[2];
std::cout << &arr[0x100];

这被认为是好的做法,还是以常规方式添加偏移量会更干净?

编辑:“工作”是指它应该在 0x100 处打印指向理论成员的指针。基本上如果这等同于“std::cout << ((unsigned int)arr + 0x100*sizeof(int));”。

最佳答案

使用我的编译器 (Cygwin GCC) 获取此值的地址与进行指针运算相同,尽管每个都是未定义行为 (UB)。正如 Jens 在下面的评论中提到的,在 http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html ,我发现以下内容很有帮助。

It is also worth pointing out that both Clang and GCC nail down a few behaviors that the C standard leaves undefined. The things I'll describe are both undefined according to the standard and treated as undefined behavior by both of these compilers in their default modes.

Dereferences of Wild Pointers and Out of Bounds Array Accesses: Dereferencing random pointers (like NULL, pointers to free'd memory, etc) and the special case of accessing an array out of bounds is a common bug in C applications which hopefully needs no explanation. To eliminate this source of undefined behavior, array accesses would have to each be range checked, and the ABI would have to be changed to make sure that range information follows around any pointers that could be subject to pointer arithmetic. This would have an extremely high cost for many numerical and other applications, as well as breaking binary compatibility with every existing C library.

指针运算也是UB。所以你有一个地址,但你不能取消引用指向它的指针。所以拥有这个地址真的没有用。只是获取地址是 UB,不应在代码中使用。

有关越界指针,请参阅此答案: Why is out-of-bounds pointer arithmetic undefined behaviour?

我的示例代码:

    int* arr = new int[2];
std::cout << arr << std::endl;
std::cout << &(arr[0])<< std::endl;
std::cout << &(arr[1])<< std::endl;
std::cout << &arr[0x100] << std::endl; // UB, cannot be dereferenced
std::cout << &arr[256] << std::endl; // cannot be dereferenced, so no use in having it
std::cout << arr + 0x100; // UB here too, no use in having this address

示例输出:

0x60003ae50
0x60003ae50
0x60003ae54
0x60003b250
0x60003b250
0x60003b250

关于C++ 数组超出范围访问计算指针有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432199/

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