簡體   English   中英

為什么在迭代大量 int 值時在我的代碼中出現此分段錯誤?

[英]Why am I getting this segmentation fault in my code while iterating through large quantities of int values?

我正在嘗試編寫的 C 程序旨在獲取一個整數值文件,並將第一個數字與第二個數字相加,然后將第一個數字與第三個數字相加,第一個數字與第四個數字相加,依此類推。 然后將第二個與第三個相加,第二個與第四個相加,依此類推。 它還意味着在添加所有數字(在我的情況下,它是 10)時,只要滿足預定值就打印一條消息,並打印出該程序執行所花費的時間。

但是,當程序開始查看我正在從中獲取值的文件中的整數列表時(該文件中有超過 10,000 個整數),它似乎進入了第 124 個循環,然后給了我一個分段錯誤(核心轉儲)錯誤。 當我將要添加的整數數量減少到 124 以下時,程序運行良好。

為什么我會收到此分段錯誤錯誤? 是我設置 While 循環的方式嗎? 有什么辦法可以解決這個問題嗎?

#include<stdio.h>
#include <time.h>
int main(){
   FILE *fptr1,*fptr2,*temp;
   fptr1 = fopen("input.txt", "r") ;
  
   int num1,num2;
   int sum=0;
   int c=0;
  
   if (fptr1 == NULL) {
       printf("File not open\n");
       return 0;;
   }
   int count=0;
  
   clock_t t;
t = clock();


// the problem seems to be in this while loop//

while(fscanf(fptr1, "%d", &num1) !=EOF){
       count++;
       fptr2 = fopen("input.txt", "r") ;
       int count1=0;
       while(fscanf(fptr2, "%d", &num2) !=EOF){
           count1++;
           if(count1>count){
               sum=num1+num2;
               if(sum==10){c++;}
           }
       }
      
   }
   
printf("sum of 10 was found in %d iterations of loop",c);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
  
printf("Time taken :%lf", time_taken);

  
   fclose(fptr1);
   fclose(fptr2);
   return 0;
}

當文件超過 124 個整數時,它給了我這個:超過 124 個整數時的輸出

當他的文件少於 124 個整數時,它給了我這個:低於 124 個整數時的輸出

問題似乎是打開了太多文件句柄,但修復應該很簡單:

while(fscanf(fptr1, "%d", &num1) !=EOF){
  count++;

  // This fopen() call might fail, you should check the result
  fptr2 = fopen("input.txt", "r");

  int count1 = 0;

  while(fscanf(fptr2, "%d", &num2) != EOF) {
    // ...
  }

  // If you open a file, you must close it before re-opening
  fclose(fptr2);
}

但是,這很浪費,沒有理由一遍又一遍地打開,而只需倒帶文件並再次使用它:

fptr2 = fopen("input.txt", "r");

while(fscanf(fptr1, "%d", &num1) !=EOF) {
  // Move back to the beginning of the file before reading
  rewind(fptr2);

  count++;

  int count1 = 0;

  while(fscanf(fptr2, "%d", &num2) != EOF) {
    // ...
  }
}

fclose(fptr2);

這里要注意的另一件事是您的變量名稱非常不透明。 fptr2沒有傳達任何關於它應該用於什么或該文件可能包含什么的信息。 如果它與輸入源相關,請考慮inputfinput甚至fin 同樣, count1count以及更神秘的c也令人困惑。 算什么? 是什么原因?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM