gpt4 book ai didi

c - 当运行大文件时,二进制搜索会溢出

转载 作者:行者123 更新时间:2023-11-30 17:11:21 25 4
gpt4 key购买 nike

void insert_tree(tree_t *tree, void *name, void *movie){
node_t *new;
new = malloc(sizeof(*new));
assert(new!=NULL);
strcpy(new->name, name);
strcpy(new->movie, movie);
new->left = new->right = NULL;
insert_node(&(tree->root), new);
}

typedef struct node node_t;
struct node{
char name[128];
char movie[422498];
node_t *left;
node_t *right;
};

typedef struct {
node_t *root;
} tree_t;

上面的代码将节点插入二叉搜索树。在对超过 200000 行的大文件运行二叉搜索树算法时,我一直遇到溢出问题。

随着

assert(new!=NULL)

声明,我发现这部分代码发生了溢出。

我猜测这是由于创建的节点太多所致?

我该如何解决这个问题?

除了这部分代码之外,我没有在任何地方使用过 reallocmalloc

所有其他代码也没有实现递归,它们都使用循环。

当文件足够小时,它可以完美地精确工作,当文件变大时,它会失败。

最佳答案

尝试让你的节点更加节省空间,拥有如此大的电影名称数组(?)是一种浪费。

而是像这样声明结构

struct node 
{
char* name;
char* movie;
nde_t* left;
node_t* right;
};

然后在你的插入函数中:

void insert_tree(tree_t* tree, const char* name, const char* movie)
{
node_t *new = NULL;

// to catch unexpected arguments
assert( tree != NULL && name != NULL && movie != NULL );

new = malloc(sizeof(node_t)); // i prefer this style for sizeof

// don't use assert for runtime errors
if (new!=NULL)
{
new->name = strdup(name); // short form for malloc/strcpy
new->movie = strdup(movie);
new->left = new->right = NULL;

insert_node(&(tree->root), new);
}
else
{
fprintf(stderr, "out of memory");
exit(EXIT_FAILURE);
}
}

您稍后应该释放每个节点的名称和电影的内存。

关于c - 当运行大文件时,二进制搜索会溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32366381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com