2014-10-21 55 views
-2

目前正在C語言中使用一致性程序。當我嘗試運行該程序時,出現錯誤。C程序雙重釋放或損壞錯誤

這是我的C程序:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 


void print(char Table, int n) { 
    printf("%d: ", n+1); // Prints the table 
} 

int insert(const void *bb, const void *cc) { 
    return strcmp(*(const char **)bb, *(const char **)cc); 
} 

void empty(char *Table[]) { 
    strcat(Table,"NULL"); // Empties the table 
} 

int main(int argc, char *argv[]){ 


    if(argc!=3){ 
     printf("ERROR: Usage: concordance table_size"); // Errors due to not enough variables (Should be tablesize and file name) 
    } else { 

     FILE *fp; //This block opens the file user has inputted and makes the string "File_contents" set to the file's contecnts 
     fp = fopen(argv[2],"r"); 
     char *file_contents; 
     long input_file_size; 
     fseek(fp, 0, SEEK_END); 
     input_file_size = ftell(fp); 
     rewind(fp); 
     file_contents = malloc((input_file_size + 1) * (sizeof(char))); 
     fread(file_contents, sizeof(char), input_file_size, fp); 
     fclose(fp); 
     file_contents[input_file_size] = 0; 

     char *word, *words[strlen(file_contents)/2+1]; 
     int i, n; 

     for(i=0;file_contents[i];i++){ 
      file_contents[i]=tolower(file_contents[i]); //Converts all words to lower case 
     } 

     i=0; 
     word = strtok(file_contents, " ,.-:;?!"); //Chars which signal end of word 

     while(word != NULL) { 
      words[i++] = word; 
      word = strtok(NULL, " ,.-:;?!"); 
     } 

     n = i; 

     qsort(words, n, sizeof(*words), insert); 

     for(i=0; i<n; ++i){ 
      print(words[i],i); 
      printf("%s\n", words[i]); 
     } 
     empty(words); 
     fclose(fp); // Closes open file 
    } 
    return 0; 
} 

而下面是我得到的錯誤:

* glibc的檢測*一致:雙重釋放或腐敗(!上一頁):0x0000000001060f010

不知道是什麼原因導致這個錯誤發生。儘管如此,任何幫助都會很大。

+3

使用任何你喜歡的工具來檢測雙重空閒和腐敗。最受歡迎的可能是'valgrind'。 – 2014-10-21 23:18:39

+2

你在調用'fclose'兩次。 – Dai 2014-10-21 23:19:48

+1

如果你的輸入文件是一個文本文件,那麼'strlen(file_contents)'等於'input_file_size'。話雖如此,功能'空'看起來有點可疑。你介意和我們分享你希望用它達到的目標嗎? – 2014-10-22 08:34:43

回答

-2

您正在將NULL作爲參數傳遞給strtok函數。我認爲這可能會導致問題

0

您沒有撥打fclose()兩次。我想這可能會在內部調用free()。在程序結束時刪除fclose()

相關問題