2013-02-09 92 views
1

我想弄清楚爲什麼我無法將文件存儲到char **中。Seg Fault char ** C

我以爲我正確分配了內存。有人可以幫幫我嗎?謝謝!另外,我知道我的方式並不是解決問題的最有效方式,但首先我想在擔心效率之前先完成問題。謝謝!

void readFile(int argc, char** argv) 
{ 
    FILE *myFile; 
    char** list; 
    char c; 
    int wordLine = 0, counter = 0, i; 
    int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0; 

    myFile = fopen(argv[1], "r"); 

    if(!myFile) 
    { 
     printf("No such file or directory\n"); 
     exit(EXIT_FAILURE); 
    } 

    while((c = fgetc(myFile)) !=EOF) //goes through the file to get # of lines 
    {         //and columns so I can allocate array 
     numberOfChars++; 
     if(c == '\n') 
     { 
      if(maxNumberOfChars < numberOfChars) 
       maxNumberOfChars = numberOfChars + 1; 

      numberOfLines++; 
     } 
    } 

    fseek(myFile, 0, SEEK_SET); //resets file pointer 

    list = malloc(sizeof(char*)*numberOfLines); //dynamically allocating 

    for(i = 0; i < wordLine ; i++) 
     list[i] = malloc(sizeof(char)*maxNumberOfChars); 


    while((c = fgetc(myFile)) != EOF)  //stores in words 
    { 
     if(c == '\n' && counter > 0) 
     { 
      list[wordLine][counter] = '\0'; 
      wordLine++; 
      counter = 0; 
     } 
     else if(c != '\n') 
     { 
      list[wordLine][counter] = c; //seg fault happens at first character 
      counter++; 
     } 
    } 
    fclose(myFile); 
} 
+0

該學習調試程序了。並做代碼評論以發現明顯的錯誤。 – 2013-02-09 10:53:43

回答

2

此時:

for(i = 0; i < wordLine ; i++) 

wordLine = 0,所以沒有存儲器將被分配。我覺得應該是:

for(i = 0; i < numberOfLines; i++) 

而且你需要設置numberOfChars = 0,類似於Grijesh肖漢說,否則你會分配太多的內存。

+0

謝謝。對不起,它是早上5點,我已經起牀了(在星期五晚上:\)從下午11點開始做功課。這樣一個愚蠢的錯誤。非常感謝捕捉。 – juice 2013-02-09 10:56:49

2

您的字線分配:

for(i = 0; i < wordLine ; i++) 
    list[i] = malloc(sizeof(char)*maxNumberOfChars); 

使用wordLine,但你在開始這個初始化爲0,這是從來沒有改變。

因此,for循環中的malloc從不執行。

1

for循環條件是亂七八糟,

for(i = 0; i < wordLine ; i++) 
    list[i] = malloc(sizeof(char)*maxNumberOfChars); 

wordLine被初始化爲0,預期它不執行和list[i]

分配內存,您可能希望將其更改爲

for(i = 0; i < numberOfLines ; i++) 
    list[i] = malloc(sizeof(char)*maxNumberOfChars);