gpt4 book ai didi

c++ - 访问无效指针并获取其地址

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:51 24 4
gpt4 key购买 nike

考虑这样的代码:

std::vector<int> vec { 1, 2, 3 };
auto addr = &*vec.end();

或简化:

int* ptr = 0;
auto addr = &*ptr;

很明显 auto val = *ptr; 会出现段错误。因此 &*ptr 不是以相同的方式访问内存。为什么会这样?标准中有专门的条目吗?

最佳答案

取消引用 std::vector::end() 的返回值是导致未定义行为的原因。尝试理解如果这样做会发生什么是没有意义的。

来自 http://en.cppreference.com/w/cpp/container/vector/end :

This element acts as a placeholder; attempting to access it results in undefined behavior.

回复。第二部分,我在 C++11 标准中唯一能找到的是:

5.3.1 Unary operators

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.” [ Note: a pointer to an incomplete type (other than cv void) can be dereferenced. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to aprvalue, see 4.1. — end note ]

取消引用 NULL 指针的结果似乎是未指定的。

关于c++ - 访问无效指针并获取其地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903533/

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