2011-03-09 53 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