这是由fopen()引起的内存泄漏吗?我使用fclose()来关闭FILE *指针,但这个问题仍然存在。
==32379== Memcheck, a memory error detector
==32379== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==32379== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==32379== Command: ./speller /home/cs50/pset6/texts/austinpowers.txt
==32379==
==32379==
==32379== HEAP SUMMARY:
==32379== in use at exit: 352 bytes in 1 blocks
==32379== total heap usage: 510,177 allocs, 510,176 frees, 57,140,478 bytes allocated
==32379==
==32379== 352 bytes in 1 blocks are still reachable in loss record 1 of 1
==32379== at 0x4006AB1: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==32379== by 0x4D9F895B: __fopen_internal (iofopen.c:73)
==32379== by 0x4D9F8A3A: fopen@@GLIBC_2.1 (iofopen.c:103)
==32379== by 0x8049061: load (dictionary.c:50)
==32379== by 0x8048759: main (speller.c:46)
==32379==
==32379== LEAK SUMMARY:
==32379== definitely lost: 0 bytes in 0 blocks
==32379== indirectly lost: 0 bytes in 0 blocks
==32379== possibly lost: 0 bytes in 0 blocks
==32379== still reachable: 352 bytes in 1 blocks
==32379== suppressed: 0 bytes in 0 blocks
==32379==
==32379== For counts of detected and suppressed errors, rerun with: -v
==32379== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
这是加载函数(fopen()调用是' dictionary.c:50'):
bool load(const char* dictionary)
{
// Open the dictionary file.
FILE* file;
file = fopen(dictionary,"r");
// If the file exists...
if(file)
{
// If the load function is called twice, this condition makes sure that we don't do it twice.
if(start==NULL)
{
start = malloc(sizeof(trie));
for(int i =0; i < 28; i++)
{
start->array[i]=NULL;
}
}
else
{
return true;
}
char c = '\0';
char* word = malloc(LENGTH+1);
while((c = fgetc(file))!=EOF)
{
int index = 0;
for(;c!='\n';index++)
{
word[index] = c;
c=fgetc(file);
}
// End the word.
word[index++] = '\0';
// now add it to the trie.
add(word);
//Increment the number of words.
numOfWords++;
}
//free the word and close the file.
free(word);
fclose(file);
return true;
}
return false;
}
答案 0 :(得分:3)
如果start
(一个全局变量?)是!= NULL,你将离开函数而不关闭文件。
答案 1 :(得分:0)
确保您确实在使用自己认为的文件。如果要将空输入文件传递给valgrind命令,则可能会有意外的行为