2011-03-09 44 views
-3
void _this() 
{ 
    string a  = "i am a"; // original value of variable a 
    string* modifier = NULL;  //pointer is declared 0x0000... 

    modifier = &a;    // 0x0000 -> 0x0a //modifier stores the address of a 
    *modifier = "modified";  // 0x0a + 0x0modified... //modifier assigns "modified" to the address of a; 

    cout << a << endl << modifier<<"\n"; //shows "modified" + the address of modifier in memory 
    modifier = NULL;      // the pointer(modifier...) now points to nothing....is it no longer "dangling"??? 
    cout << modifier;     // shows only zeros...000000000 
} 
+2

我不明白这个问题,代码太复杂了。 – 2011-03-09 19:46:22

+2

*为什么*你会写这样的代码吗?它有什么用处? – birryree 2011-03-09 19:47:03

+4

C中没有'string';也没有'cout'和'<<'的用法很简单:删除了'c'标签 – pmg 2011-03-09 19:47:13

回答

3

我打算假设你使用C++而不是C,而当你说字符串时,你的意思是::std::string

上面的代码中没有显示内存泄漏。

另外,悬挂指针只有在对象超出范围或被删除时才有意义。你在这里既没有这些东西。

+0

嗨。谢谢。是的,这是一个C++代码,但我标记为C,因为指针概念是与c/C++相关的时间的90%。我现在看到,但我的想法正是如此。 – someoneyeah 2011-03-09 20:05:03

0

代码中没有悬挂指针。在几条线上,左边(第一个)评论是错误的,而第二条评论是正确的。例如//0x0000 -> 0x0a //modifier stores the address of a:在该行之后,modifier保存变量a的地址,该地址几乎肯定不同于物理地址0x0a

2

一个悬挂指针是指向无效内存的指针(不是NULL)。通常与最初指向有效内存的指针相关联。

int x = new int(4); // x valid; 
delete x;    // x is now dangling. 
         // It points at memory that does not belong to application 

x = NULL;    // x is not dangling. 

在你原来的例子指针永远吊着因为它指向一个自动变量,将永远是有效的(而修改是有效的)。虽然如果你返回修改作为结果从函数,然后将悬垂(如果你还没有分配NULL)。

在C中删除指针后为NULL指定NULL在C中非常重要。但在C++中没有这么多,因为指针应该封装在类中,以便在使用完成后它不再可用。

std::string data; // There is a pointer inside here. 
         // No need to set it to NULL. The destructor handles all that. 
+0

10倍......现在“更清晰了......”因此,对象应该总是超出范围或被删除,指针变成悬空。 – someoneyeah 2011-03-09 20:07:55