我一直在弄清楚爲什麼我得到這個錯誤。以下是代碼片段:我不確定爲什麼我得到NULL指針解除引用錯誤
int main() {
node *root = NULL;
char item1[6];
int item2;
in.open("input.txt");
while(in >> item1) {
if(strcmp(item1, "delete") == 0) {
in >> item2;
cout << root->item << endl;
if(!deleteLeaf(root, item2)) { // if deleteLeaf did not find(false)
}
}
else {
item2 = atoi(item1);
Insert(root, item2);
cout << root->item << endl;
}
}
return 0;
}
我注意到那是什麼第一cout << root->item << endl;
被認爲是一個空指針引用錯誤,但爲什麼不是第二個?我注意到,如果我也將cout << root->item << endl;
更改爲cout << root << endl;
,我會得到兩個不同的地址位置。下面是插入()的代碼:
void Insert(node *&leaf, int item) {
if(leaf == NULL) {
leaf = new node;
leaf->right = NULL;
leaf->left = NULL;
leaf->item = item;
}
else if(item < leaf->item) {
Insert(leaf->left, item);
}
else {
Insert(leaf->right, item);
}
}
這是輸入文件:
1
2
delete 3
4
5
6
爲背景,這個代碼應該從輸入文件讀取和使用雙創建一個二叉樹鏈表。如果我讀到「刪除」一詞,我需要搜索列表並刪除該項目,如果它不存在,那麼我需要創建節點。我不明白的是爲什麼cout < < root < < endl給我兩個不同的地址?
如果您需要更多的信息,我會很樂意提供。
編輯:我第一次,我認爲這是一個空指針解引用錯誤,導致我得到node *root
兩個不同的地址位置的問題,但它實際上是我的數組大小設置爲6而不是7,導致溢出意外更改地址位置。謝謝你們的幫助!
我還是新來的StackOverflow,所以我不知道如何解決爲紀念這個...
除了你所問的問題:「刪除」需要7個字符來存儲'item1',它是一個char [6]'。只要鍵入「delete」,數組就會溢出,導致內存損壞和未定義的行爲。 –
@SamVarshavchik,我很慚愧。我不敢相信我忽略了一個數組溢出問題。這就解釋了爲什麼我遇到了兩個不同的「root」地址位置。非常感謝你 – byu2899
[不要使用'endl',除非真的需要](http://stackoverflow.com/q/213907/995714) –