2015-01-21 79 views
0

我想写一个包装从文件中取一些预定义的标准输入。如果开头有'#',程序应该跳过一行,否则将除了前2个元素之外的所有元素存储在称为factorList的数组中。 我正在使用malloc来动态分配内存到这个指针。 我然后试图访问这个数组之外的while循环,我声明它,但它导致一个错误。malloc内存无法访问外循环

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

int main(int argc, char * argv[]) 
{ 
    int degree = 100; 
    int tempDegree; 
    int num; 
    int * factorList; 
    FILE * primeFile = fopen(argv[1],"r"); 
    if(!primeFile) 
    { 
     printf("Could not open file containing prime table\n"); 
    } 
    char store[100] = {0}; 
    char lineCheck = ' '; 
    int primeCheck = fscanf(primeFile, "%s", store); 

    while(primeCheck != EOF) 
    { 
     if(strcmp("#",store) == 0) 
     { 
      printf("Mark1\n"); 
      // Clearing Store array 
      memset(store, 0 , sizeof(store)); 
      // Skip this line 
      while((lineCheck != '\n') && (primeCheck != EOF)) 
      { 
       primeCheck = fscanf(primeFile, "%c", &lineCheck); 
      } 

      lineCheck = ' '; 
      // Reading the start of the next line 
      if(primeCheck != EOF) 
      { 
       primeCheck = fscanf(primeFile, "%s", store); 
      } 
     } 
     else 
     { 
      tempDegree = atoi(store); 
      if(tempDegree == degree) 
      { 
       printf("Mark2\n"); 
       // This is the list of primes 
       primeCheck = fscanf(primeFile, "%d", &num); 
       factorList = malloc(sizeof(int)*num); 
       int i; 
       for(i=0;i < num; i++) 
       { 
        primeCheck = fscanf(primeFile, "%d", &factorList[i]); 
        printf("%d",factorList[i]); 
       } 
       break; 
      } 
      else 
      {  
       printf("Mark3\n"); 
       // Clearing Store array 
       memset(store, 0 , sizeof(store)); 
       // Skip this line 
       while((lineCheck != '\n') && (primeCheck != EOF)) 
       { 
        primeCheck = fscanf(primeFile, "%c", &lineCheck); 
       } 
       lineCheck = ' '; 
       // Reading the start of the next line 
       if(primeCheck != EOF) 
       { 
        primeCheck = fscanf(primeFile, "%s", store); 
       } 
      } 
     } 

     // Testing Access to factorList , getting error here. 
     int i = factorList[0]; 
    } 
    return 0; 
} 
+0

'strcmp(“#”,store)== 0'将检查整行是否正好是'#'...不只是第一个字符。改为使用'store [0] =='#''。 – 2015-01-21 03:53:43

+0

它仅在一个条件上分配,在其他情况下,该列表将为NULL,在访问它之前检查NULL – radar 2015-01-21 03:53:59

+0

您的循环非常复杂;而不是在循环之前读取第一行,并让循环中的每条代码路径读取下一行的开始,您应该在循环的开始处读取行的开始(并且如果出现错误,break; '出)。 – 2015-01-21 03:55:09

回答

1

线:

// Testing Access to factorList , getting error here. 
    int i = factorList[0]; 

不是while循环的外部。它位于循环的底部,因此循环的每次迭代都会执行一次。

循环内部是一个分支。分支的'真正'部分,如果仅读取一行'#'的行,则不会将任何内容分配给factorList。因此,如果在循环的第一次迭代中遇到'#',则程序可能会崩溃,因为您正在取消引用未指定值的指针,引发未定义的行为。

在假分支中,还有另一个分支。该分支的错误部分也不会将任何东西分配给factorList,因此如果tempDegree ==度在第一次迭代中不是真的,则会发生同样的情况。

还有其他一些需要改进的地方,我会密切关注您的问题的一些意见。

+0

我没有看到,现在工作。谢谢 – 2015-01-21 04:37:39