我试图弄清楚如何在二叉树中插入大量数字。 程序通过询问一个数字开始,并将0插入用户输入的任何数字。我的程序工作但它开始崩溃大约40,000我得到错误: 流程返回-1073741571(0XC00000FD)
我是C和内存管理的新手,但我相信问题就在那里。任何建议?
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node BSTREE;
struct node
{
int data;
struct node * left;
struct node * right;
};
void insert(BSTREE ** root, int number);
int main()
{
BSTREE *root = malloc(sizeof *root);
BSTREE *tmp = malloc(sizeof *root);
root = NULL;
int x;
int input;
FILE *fp;
fp=fopen("c:\\test2.txt", "w");
printf( "Please enter a number: " );
scanf( "%d", &input );
for ( x = 0; x < input; x++ )
{
insert(&root, x);
}
printf("%d", x);
free(root);
fclose(fp);
}
void insert(BSTREE ** root, long int number)
{
BSTREE *temp = NULL;
if(!(*root))
{
temp = (BSTREE *)malloc(sizeof(BSTREE));
temp->left = temp->right = NULL;
temp->data = number;
*root = temp;
return;
}
if(number < (*root)->data)
{
insert(&(*root)->left, number);
free(root);
}
else if(number > (*root)->data)
{
insert(&(*root)->right, number);
free(root);
}
free(root);
}
答案 0 :(得分:0)
每次调用insert时,您都会调用free(root)
两次。在insert
返回后立即执行。然后立即再次在同一节点上。并且您似乎总是自由地使用您刚刚插入的节点。因此,你的记忆可能已经腐败,恰好在小树上工作。随着树的变大,内存开始重新分配,树腐败变得更加明显。
这是一个更简单的解决方案。它更详细,但在一个函数中处理malloc和free,而核心递归插入在另一个函数中完成。希望这会有所帮助。
extern int insert_node(BSTREE* root, BSTREE* node);
void insert(BSTREE** root, int number)
{
/* allocate a node for our number to be inserted */
BSTREE* node = malloc(sizeof(BSTREE));
node->data = number;
node->left = NULL;
node->right = NULL;
int insert_result;
if (*root == NULL)
{
/* handle the empty tree case */
*root = node;
return;
}
insert_result = insert_node(*root, node);
if (!insert_result)
{
/* insert_node returned false.
This means it already had a duplicate of the node
in the tree. Just free it since it did not get inserted
*/
free(node);
node = NULL;
}
}
int insert_node(BSTREE* root, BSTREE* node)
{
int result = 1; /* success */
if (node->data < root->data)
{
/* traverse left */
if (node->left != NULL)
{
result = insert_node(root->left, node);
}
else
{
root->left = node;
}
}
else if (node->data > root->data)
{
/* traverse right */
if (node->right != NULL)
{
result = insert_node(root->right, node);
}
else
{
root->right = node;
}
}
else
{
/* else node is equal to root - nothing to do */
/* return 0 to indicate the node should be free'd by the caller*/
result = 0;
}
return result;
}