是否使用无效的指针初始化指针声明符未定义的行为? [英] Is initializing a pointer declarator with an invalid pointer undefined behavior?

查看:120
本文介绍了是否使用无效的指针初始化指针声明符未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,以下代码是否被认为具有未定义的行为?

In short, is the following code considered to have undefined behavior?

int main()
{
    int *p = <some invalid pointer value>;
}

对于一个编译示例,请采用以下代码:

For a compiling example, take the following code:

int main()
{
    int *p = new int;
    delete p; // Now p has an invalid pointer value.
    int *q = p; // UB?
}

我已经对该主题进行了一些研究,所以这些是我到目前为止发现的相关信息:

I've done some research on the topic, so these are the relevant information I've found so far:

指针值(根据 cppreference )可以是以下之一:

A pointer value (according to cppreference) can be one of:

  • 指向对象或函数的指针;
  • 一个指向对象末尾的指针;
  • 空指针值;
  • 无效的指针值.

此外,根据cppreference,

Also, according to cppreference,

通过无效的指针值进行的间接传递以及将无效的指针值传递给释放函数均具有未定义的行为.任何其他使用无效指针值的行为都有实现定义的行为.

Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

此线程解决了无效指针的一些用法.具体来说,此答案提到

This thread addresses some uses of invalid pointers. Specifically, this answer mentions the Rationale document (C99), which has the following paragraph (section 6.3.2.3):

无论如何创建无效的指针,对其的任何使用都会产生未定义的行为.甚至赋值,与空指针常量进行比较或与自身进行比较,在某些系统上也可能导致异常.

Regardless how an invalid pointer is created, any use of it yields undefined behavior. Even assignment, comparison with a null pointer constant, or comparison with itself, might on some systems result in an exception.

我不确定C ++的状况如何,但是我认为,鉴于链接线程的答案,使用会导致不确定的行为.但是请注意,赋值初始化不同,因此我不确定初始化是否被认为有用.

I'm not sure what's the state of affairs for C++, but I'd consider that, given the answers on the linked thread, uses of invalid pointers result in undefined behavior. Note, though, that assignment is not the same as initialization, so I'm not sure initialization is considered a use.

推荐答案

您自己都回答了这个问题:它是在C ++中实现定义的而不是未定义的.该标准说只是您引用的内容(我通过咨询适当的索引).是否初始化都没关系:左值到右值转换在指针对象上明确地构成了一种用途.

You’ve all but answered this yourself: it’s implementation defined, not undefined, in C++. The standard says just what you quoted (which I found by consulting the appropriate index). It doesn’t matter whether it’s initialization: the lvalue-to-rvalue conversion on the pointer object explicitly constitutes a use.

这篇关于是否使用无效的指针初始化指针声明符未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆