2013-02-09 94 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);