2015-05-01 57 views
0

我有一個名爲「StatusInformation」的類,我想將變量_status設置爲true/false,但我僅獲得「分段錯誤」。我認爲,_status不存在,因爲我從其他課程中調用它。任何人都知道如何防止這個錯誤?來自其他類的安裝程序

StatusInformation.cpp

void StatusInformation::SetClientConnectStatus(bool status) 
{ 
    _status = status; 
} 

StatusInformation.h

class StatusInformation 
{ 
private: 

    bool _status = false; 

public: 

    void SetClientConnectStatus(bool status); 
}; 

CallerClass.cpp

_statusInformation = new StatusInformation(); 

_statusInformation->SetClientConnectStatus(true); 

CallerClass.h

StatusInformation *_statusInformation; 
+1

這顯然不是你的所有代碼,也沒有足夠的答案給出明智的答案。 – John3136

+0

你說得對,這不是我的全部代碼,我應該給你4050行代碼嗎?這是重要的代碼,其他代碼並不重要,因爲它在沒有此代碼的情況下工作。 – ForJ9

+0

你爲什麼要在頭文件中放一個指針聲明? – Qix

回答

1

編輯︰到您的代碼的鏈接只是給我缺少ArduinoProtocol的代碼。

對我來說,這個編譯有2個關於非靜態數據成員初始值設定項的警告,然後運行正常。我真的不相信分段錯誤可能來自此代碼。唯一可能導致的原因是

_statusInformation = new StatusInformation(); 

失敗並返回0,使您的指針成爲空指針。曹景偉:

_statusInformation->SetClientConnectStatus(true); 

等同於:

NULL->SetClientConnectStatus(true); 

但是,這隻能發生,如果您選擇使用一個沒有拋出新的。你指定的很多。所以現實地說,代碼中唯一可能會導致分段錯誤的事情不會發生。最糟糕的情況是std :: bad_alloc會被拋出。

+0

我看到我的錯誤,謝謝你的提示。我在構造器中創建了一個新線程,並等待同步。這給了我一個NULL指針 – ForJ9

+0

所以你實際上得到一個NULL指針?呵呵。我也無法編譯完整的代碼來運行它的valgrind。 (哦,是的,檢查未來所有分段故障valgrind。) – Khaldor

+0

晚上會回來。如果這只是一個分段錯誤,無論何時你正在做c/C++並且想要更近一些地看看內存中發生了什麼,請查看valgrind http://valgrind.org/ brilliant。 – Khaldor