2016-04-30 48 views
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,但我不知道這意味着什麼

+1

也許在完成時關閉文件將有助於檢查您是否已成功打開文件 –

+0

關閉文件並不重要,因爲代碼目前甚至沒有達到可以關閉任何內容的程度。並且openFiles中的if語句完全用於確保文件實際上已打開 –

+2

您沒有正確使用'calloc',請參閱我的更改。 – fluter

回答

2

這條線是有問題的:

freq->files = calloc(1,sizeof(FILE**)); 

按照sturct,您將需要一個FILE*每個的文件,但是這一行只分配一個FILE**,改爲:

freq->files = calloc(freq->numFiles, sizeof(FILE*)); 
+0

這樣做!我之前分配的東西不同,並根據我的一位朋友的建議改變了這一點。有趣的是,直到我獲得更大的文件數量,這並不重要 –

相關問題