我实现了一个树,其节点看起来像这样:
typedef struct node_s {
struct node_s *parent;
struct node_s *left;
struct node_s *right;
data_t *data;
}node_t;
其中*data
指向带有key
的数据结构,该数据结构用于对树进行排序。
当我添加一个新节点时,它看起来像这样:
node_t *add_Item (node_t *root){ //root is the root of the tree
...
data_t *new_data;
new_data = calloc(1,sizeof(data_t));
if(!new_data){
... //Error handling
}
root = insert_Node(root, new_data);
... //modifying new_data
return root;
}
node_t insert_Node(node_t *root, data_t *data){
... \\tree traversing and searching
if(root->data->key == data->key){ \\if the key is already in the tree it should be replaced
data_t *temp_data = root->data;
root->data = data;
free(temp_data); \\freeing the old data
}
...
return root;
}
我不了解 free(temp_data)
不起作用。另外,调试信息对我来说没有意义:
temp_data = 0x0000024C856DA950
root->data = 0x0000024C856DA9D0
HEAP[Program.exe]: Invalid address specified to RtlValidateHeap( 0000024C856D0000, 0000024C856DA920 )
错误消息中的地址总是0x30
小于temp_data
。只要能帮助任何人:Windows 10,Visual Studio
编辑-最小的可复制示例
#include <stdio.h>
#include <stdlib.h>
typedef struct data_s {
long key;
}data_t;
typedef struct node_s {
struct node_s* parent;
struct node_s* left;
struct node_s* right;
data_t* data;
}node_t;
node_t* init_node(data_t* data) {
node_t* new_node;
if ((new_node = calloc(1, sizeof(node_t)))) {
new_node->data = data;
fprintf(stderr, "node created\n");
}
return new_node;
}
node_t* insert_node(node_t* root, data_t* data) {
node_t* node;
if (root) {
if (root->data->key == data->key) {
printf("This item alreay exists!\n%ld will be replaced!\n", data->key);
data_t* temp_data;
temp_data = root->data;
root->data = data;
free(temp_data);
}
else if (root->data->key > data->key) {
node = insert_node(root->right, data);
root->right = node;
node->parent = root;
}
else {
node = insert_node(root->left, data);
root->left = node;
node->parent = root;
}
}
else {
root = init_node(data);
}
return root;
}
int main(int argc, char** argv) {
data_t* data;
node_t* root = 0;
while (1) {
if (!(data = calloc(1, sizeof(data_t)))) {
return(EXIT_FAILURE);
}
printf("What is the key for the new data?\n");
scanf("%ld", &(data->key));
root = insert_node(root, data);
//there would be more editing of data afterwards
}
return(EXIT_SUCCESS);
}
这似乎可行,但我不知道为什么可行,而我的其他程序却无效。