【发布时间】:2023-04-04 08:05:01
【问题描述】:
我正在学习 cs50x 课程,做拼写检查程序。在我第四次执行这个程序时,我遇到了 malloc 问题。 这次我决定实现一个二叉树。 我已经阅读了很多关于这个问题的线程并多次检查了我的代码,但我仍然无法理解我做错了什么。 问题出现在将字典加载到内存中的递归函数中。
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"
// standart node of the trie
typedef struct node
{
char word[LENGTH + 1];
struct node* less;
struct node* more;
}
node;
// Function definitions
void unload_node(node* pr_node);
void ld_bin_tree(int min, int max, node* node);
bool check_word(char* lword, node* parent);
// Global variables
// root of the tree
node* root;
FILE* dict;
//size of dictionary
int dict_size = 0;
bool load(const char* dictionary)
{
// open dictionary file
dict = fopen(dictionary, "r");
int nwords = 0;
int min = 0;
int max = 0;
root = malloc(sizeof(node));
//if file wasn't open
if(dict == NULL)
{
printf("Error opening ditionary file!");
return false;
}
// tmp storage for read word
char buffer[LENGTH + 1];
// count words in the dictionary
while(fscanf(dict, "%s", buffer) > 0)
{
nwords++;
}
max = nwords;
rewind(dict);
ld_bin_tree(min, max, root);
// close file
fclose(dict);
return false;
}
/*
* Recursion function to fill in binary tree
*/
void ld_bin_tree(int min, int max, node* node)
{
// tmp word holder
char buffer[LENGTH + 1];
// next mid value
int mid = (min + max) / 2;
// if mid == 0 then the bottom of the brunch reached, so return
if(max - min < 2)
{
if(min == 0)
{
fscanf(dict, "%s", node->word);
dict_size++;
return;
}
return;
}
// go through the dict to the mid string
for(int i = 0; i <= mid; i++)
{
fscanf(dict, "%s", buffer);
}
// fill in word
strcpy(node->word, buffer);
// go at the beginning of the dict
rewind(dict);
// fill in input node
// fill in new children nodes
struct node* new_node = malloc(sizeof(node));
node->less = new_node;
// send lesser side
ld_bin_tree(min, mid, node->less);
new_node = malloc(sizeof(node));
node->more = new_node;
// send greater side
ld_bin_tree(mid, max, node->more);
dict_size++;
return;
}
我尝试使用 valgrind 解决此错误,但它给了我很多关于在未分配的内存块中读取和写入的警告。但是因为我还不太擅长编程,所以这个警告并没有让我知道发生了什么。
因此,如果可能的话,我正在寻求更准确的帮助。提前谢谢你。
拼写程序的其他部分可以在这里找到: https://www.dropbox.com/sh/m1q1ui2g490fls7/AACnVhjjdFpv1J0mUUhY2uV2a?dl=0
【问题讨论】: