這是用於學校作業。當我嘗試向BST添加新節點時,我遇到了seg故障。我認爲這可能與我如何分配內存有關,但我無法弄清楚如何解決這個問題。將節點添加到BST字符串
STRUCT代碼:
struct tnode {
char* data;
struct tnode* left;
struct tnode* right;
};
typedef struct tnode Tnode;
添加節點功能:
Tnode* add_tnode(Tnode* current_tnode, char* value) {
if (current_tnode == NULL) {
malloc(sizeof(Tnode));
current_tnode->data = value;
current_tnode->left = NULL;
current_tnode->right = NULL;
return current_tnode;
}
else {
if (strcmp(current_tnode->data, value) <= 0) {
add_tnode(current_tnode->left, value);
return current_tnode->left;
}
else {
add_tnode(current_tnode->right, value);
return current_tnode->right;
}
}
}
主程序來測試功能:
int main() {
Tnode* new_node = (Tnode*)malloc(sizeof(Tnode));
char* data1 = "Hello";
char* data2 = "Goodbye";
char* data3 = "Hi";
char* data4 = "Bye";
char* data5 = "Hey";
add_tnode(new_node, data1);
add_tnode(new_node, data2);
add_tnode(new_node, data3);
add_tnode(new_node, data4);
add_tnode(new_node, data5);
return 0;
}
這是我收到錯誤時,我回溯分割故障:
#0 0x0000003458478350 in strcmp() from /lib64/libc.so.6
#1 0x00000000004005be in add_tnode (current_tnode=0x601010,
value=0x400708 "Hello") at tree.c:16
#2 0x0000000000400523 in main() at treetest.c:12
我在想,當strcmp()試圖找到存儲在節點中的字符串時,它找不到它。任何幫助或提示將非常感激!
你試過使用調試器嗎? – 2013-02-17 21:51:39
是的,我是如何回到我的seg故障的。 – 2013-02-17 21:55:04
那麼,下次檢查生成/更改的數據結構,並檢查到底發生了什麼。 – 2013-02-17 21:58:32