2012-05-10 100 views
0

每當我輸出特定的指針地址std::cout,我得到一個崩潰:什麼可能導致寫指針地址到std :: cout崩潰?

bool MyClass::foo() const 
{ 
    std::cout << "this prints fine" << std::endl << std::flush; 
    std::cout << d << std::endl << std::flush; // crash! 
    return true; 
} 

哪裏d是類的指針成員,即:

class MyClass { 
// ... 
private: 
    MyClassPrivate* d; 
}; 

什麼會導致應用程序崩潰?即使它是一個NULL指針或初始化指針,它仍然應該打印出(也許是無效的)地址,對吧?

應用程序在調試模式下編譯,如果這有所幫助。功能foo未標記爲內聯。

背景:我試圖追蹤外部應用程序進程中的錯誤。該錯誤僅在另一個應用程序向該進程發送快速命令時引起。我使用std::cout來追蹤外部進程的執行情況。

+0

也許你有operator <<(ostream&,MyClassPrivate *)定義?這將導致它被稱爲 – killogre

+0

你可以告訴崩潰是在'operator <<'還是在'foo()'中? – zneak

+2

*旁白*:'std :: endl'已經執行了'std :: flush'。代碼中的std :: flush是多餘的。 –

回答

4

如果this不是有效指針,則對成員字段的任何訪問都可能導致訪問衝突。在無效指針上調用的非虛方法工作得很好,直到他們嘗試訪問一個字段,因爲調用本身不需要取消引用this

舉例來說,這種情況大概會崩潰,因爲你描述:

MyClass* instance = nullptr; // or NULL if you're not using C++11 
instance->foo(); // will crash when `foo` tries to access `this->d` 
+0

爲了測試這個理論,添加'std :: cout <<(void *)這個<< std :: endl'。 –

+0

謝謝,這似乎是這樣的:'std :: cout <<(void *)這個<< std :: endl'也失敗。我應該更多地關注「C++對象模型內部」。 :) –

3

有可能是operator<<(ostream &, MyClassPrivate*)過載,即取消引用指針。例如,當然有MyClassPrivate確實是char

嘗試std::cout << (void*)d;,看看它是否有所作爲。如果沒有,zneak的答案似乎是合理的。

相關問題