什么是悬挂指针 [英] What is a dangling pointer

查看:185
本文介绍了什么是悬挂指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是很常见的问题,但对我来说仍然是新的!

I know this is pretty common question, but still new for me!

我不明白悬挂指针的概念,正在搜索,写测试方法
找到一个...我只是想知道这是一个悬挂指针吗?无论什么例子,我发现是返回
的东西,这里我正在尝试类似的东西!
谢谢!

I don't understand concept of dangling pointer, was googling around, and writing test methods to find one ... I just wonder is this a dangling pointer? As whatever example I found was returning something, here I'm trying something similar! Thanks!

void foo(const std::string name)
{
    new_foo(name.c_str()); ///// will it be Dangling pointer?!, with comments/Answer
                           ///// it could be if in new_foo, I store name into Global.
                           ///// Why?! And what is safe then?
}

void new_foo(const char* name)
{
    ... print name or do something with name...   
}


推荐答案

悬挂指针是指向无效数据的指针,数据无效,例如:

A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:

Class *object = new Class();
Class *object2 = object;

delete object;
object = nullptr;
// now object2 points to something which is not valid anymore

堆栈分配的对象:

Object *method() {
  Object object;
  return &object;
}

Object *object2 = method();
// object2 points to an object which has been removed from stack after exiting the function

如果字符串之后被修改或销毁, c_str 返回的指针可能会变得无效。在你的例子中你似乎没有修改它,但由于它不清楚你要做什么与 const char * name 这是不可能知道它的代码本质上

The pointer returned by c_str may become invalid if the string is modified afterwards or destroyed. In your example you don't seem to modify it, but since it's not clear what you are going to do with const char *name it's impossible to know it your code is inherently safe or not.

例如,如果将指针存储在某个位置,然后相应的字符串被销毁,则指针将变为无效。如果在 new_foo (例如,为了打印的目的)范围内使用 const char * name 将保持有效。

For example, if you store the pointer somewhere and then the corresponding string is destroyed, the pointer becomes invalid. If you use const char *name just in the scope of new_foo (for example, for printing purposes) then the pointer will remain valid.

这篇关于什么是悬挂指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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