这是为了学校作业。当我尝试将新节点添加到 BST 时出现段错误。我认为这可能与我分配内存的方式有关,但我不知道如何解决这个问题。
结构代码:
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() 试图找到存储在节点中的字符串时,它找不到它。任何帮助或提示将不胜感激!