2015-01-21 85 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