我的代码有问题。我想加载一个可以正常工作的字典。但是当我尝试加载更大的版本时,我的while循环停在第701个单词“acclimatization”,然后程序继续。我在论坛上搜索了很多东西并尝试了很多东西,但我找不到造成这种情况的原因。有没有人知道这是怎么发生的?
Dictionary.c
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *formatedDate = [dateFormatter stringFromDate:self.DatePicker.date];
self.SelectedDate.text =formatedDate;
self. DatePicker.hidden=NO;
节点由:
定义bool load(const char* dictionary)
{
// reserve space for word
char* word = malloc(sizeof(char*));
// open file
FILE* dict = fopen(dictionary, "r");
if (dict == NULL)
{
fclose(dict);
fprintf(dict, "Could not load %s.\n", dictionary);
return 1;
}
root = (struct node *) malloc(sizeof(struct node));
root->is_word = false;
//Loops over word aslong the EOF is not reached
while (fgets(word,LENGTH,dict) != NULL)
{
printf("word = %s\n", word);
int word_length = strlen(word) -1;
node* current = root;
word_count++;
//Loops over letters
for (int i = 0; i < word_length; i++)
{
int index;
node *next_node;
// checks if letter isnt a apostrophe
if(word[i] == 39)
{
index = MAX_CHARS - 1;
}
// gets nummeric value of letter
else
{
index = tolower(word[i]) - 'a';
}
next_node = current->children[index];
// creates new node if letter didnt exists before
if(next_node == NULL)
{
next_node = malloc(sizeof(node));
current->children[index] = next_node;
current->is_word = false;
printf("new letter: %c\n", word[i]);
}
else
{
printf("letter: %c\n", word[i]);
}
// checks for end of the word
if(i == word_length - 1)
{
next_node->is_word = true;
}
current = next_node;
}
}
return true;
}
答案 0 :(得分:4)
char* word = malloc(sizeof(char*));
根据平台,它可以是4
或8
。您需要分配更多内存。
char* word;
word = malloc(LENGTH); // LENGTH as you use it here while (fgets(word,LENGTH,dict) != NULL)
if(word!=NULL){ // and checking if malloc is successful
// your code
free(word); // freeing allocated memory
return true;
}
else { // executed only if malloc fails
//handle error
}
您可以提供任何所需的尺寸。
注意 - 使用函数free()
,每次分配内存时都需要释放。
答案 1 :(得分:2)
您为word
分配的空间非常小,可能是8
或4
字节,具体取决于您的平台。
您正在为 1 char
指针分配空间,因此当您从文件LENGTH
字符读取时,您可以存储超出分配缓冲区限制的字节。问题是,行为未定义因此程序可能会起作用,或者可能会停止或发生任何事情。
你不需要动态分配它,就像这样,没关系
char word[100];
while (fgets(word, sizeof(word), file) != NULL) ...
/* ^ this only works with arrays, */
/* the benefit is that you can */
/* change the definition of word */
/* and resize it without changing */
/* this part. */
/* */
/* It will NOT work if you use `malloc()' */
此外,如果fopen()
失败,您将遇到内存泄漏,每malloc()
个free()
需要相应的for (int i = 0; i < word_length; i++)
。
<强>建议强>:
for (int i = 0; ((word[i] != '\n') && (word[i] != '\0')); i++)
也可以这样写出
strlen()
并且你避免调用userEnvironments
,它也会遍历字符。