【发布时间】:2015-09-04 13:08:35
【问题描述】:
我的程序有内存泄漏,但我想我已经找到了它的原因。我正在做的是使用 concat 函数将标准输入中的所有单词添加到一个字符串中。
这是一个函数:
Word* readWords(FILE *file) {
char buffer[201];
char* all_words_string = "";
Word* word_node_list = NULL;
char* cp = fgets(buffer, 201, file);
while (cp != NULL) {
all_words_string = concat(all_words_string, cp);
cp = fgets(buffer, 201, file);
}
char** word_list = wordList(all_words_string); //You can probably ignore this
free(all_words_string);
word_node_list = count_words(word_list); //Ignore this
freeWordList(word_list); //Ignore this
free(word_list); //Ignore this
return word_node_list;
}
调用concat函数:
char* concat(char *s1, char *s2){
char *result = malloc(strlen(s1)+strlen(s2)+1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
我认为是 while 循环
while (cp != NULL) {
all_words_string = concat(all_words_string, cp);
cp = fgets(buffer, 201, file);
}
对我的内存泄漏负责。因为我在 concat 中分配了所有这些空间,然后删除指向它的指针,然后我只释放 this 的最后一个实例。
这是我的内存泄漏的原因吗?如果是这样,我该如何解决?
【问题讨论】:
标签: c memory-leaks