C 使用大文件运行时,二进制搜索溢出
上面的代码将节点插入到二叉搜索树中。我在运行二进制搜索树算法时遇到了溢出的问题,该算法包含超过200000行的大文件 和C 使用大文件运行时,二进制搜索溢出,c,C,上面的代码将节点插入到二叉搜索树中。我在运行二进制搜索树算法时遇到了溢出的问题,该算法包含超过200000行的大文件 和 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, mo
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;
语句,我发现溢出发生在这部分代码中
我猜这是因为创建了太多的节点
我如何解决这个问题
除了这部分代码之外,我没有在任何地方使用过realloc和malloc
所有其他代码也不实现递归,它们都使用循环
当文件足够小时,它可以精确地工作。当文件变大时,它会失败。请尝试使节点更节省空间,为电影名称提供如此大的数组是一种浪费 而是像这样声明结构
assert(new!=NULL)
然后在插入函数中:
struct node
{
char* name;
char* movie;
nde_t* left;
node_t* right;
};
稍后,您应该为每个节点释放名称和电影的内存。请在问题中添加节点的定义。溢出是什么意思?你是说撞车吗?malloc返回NULL?错误的结果?等确切的行为是什么?char-movie[422498]和strcpynew->movie,movie;是可疑的和浪费的。它崩溃了,我认为这是由于mallocWell的内存溢出,正如在另一条评论中提到的,您的节点大小很大。每个节点大约400k。在200000个节点上,需要大约8GB的内存。您可能应该做的是将电影设置为char*,并动态分配内存,使其足以容纳每个字符串。strndup可以帮你。
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);
}
}