0
我正在研究設計用於處理任意數量輸入文件的字頻程序。它適用於較小數量的文件,即使這些文件有成千上萬的文件,但是當試圖用更大數量的文件(在我測試的情況下爲24)運行它時,它幾乎甚至不能從第一個文件在segfaulting之前。大量輸入文件導致程序根本無法運行
typedef struct {
int noInFiles, numFiles, numToPrint;
char** fileNames;
FILE** files;
Hash hash;
} Freq;
void openFiles(Freq* freq) {
int i;
char* str;
freq->files = calloc(1,sizeof(FILE**));
for(i = 0; i < freq-> numFiles; i++) {
freq->files[i] = fopen(freq->fileNames[i],"r");
if(freq->files[i] == NULL) {
str = malloc(strlen(freq->fileNames[i]) + 5);
sprintf(str,"wf: %s",freq->fileNames[i]);
perror(str);
free(str);
exit(EXIT_FAILURE);
}
}
}
void wordCount(Freq* freq) {
int i, totalWords = 0;
char *word = NULL;
unsigned wordLength = 0, memSize = 0;
for(i = 0; i < freq->numFiles; i++) {
fprintf(stderr,"Counting from file %d named %s\n", i,freq->fileNames[i]);
while(EOF != getWord(&word, &wordLength, &memSize, freq->files[i], "file"))
{
addEntry(&(freq->hash), word, 1);
totalWords++;
free(word);
word = NULL;
}
}
freq->totalWords = totalWords;
}
Valgrind的說,openFiles散有Invalid write of size 4
,但我不知道這意味着什麼
也許在完成時關閉文件將有助於檢查您是否已成功打開文件 –
關閉文件並不重要,因爲代碼目前甚至沒有達到可以關閉任何內容的程度。並且openFiles中的if語句完全用於確保文件實際上已打開 –
您沒有正確使用'calloc',請參閱我的更改。 – fluter