2017-03-12 108 views
-1

我正在編寫一個程序來將數字從十進制轉換爲二進制。我已經有了正確的算法,並且使用cout時程序工作正常。但是,只要我在循環中使用outfile,程序就會崩潰,出現錯誤代碼(0xC0000005)。 這裏是我的源代碼:Outfile導致內存衝突崩潰

通過訪問一個元素外的界限
#include <iostream> 
#include <iomanip> 
#include <fstream> 
#include <cmath> 
using namespace std; 

int main() 
{ 
    int num, remainder_count; 
    ifstream infile; //define new input file stream 
    ofstream outfile; //define new output file stream 

    infile.open("C:\\Users\\Arctic-Gaming\\CLionProjects\\working\\Source\\Binary Conversion (Loop w File)\\Binary Input.txt"); //connect the stream to an actual file 
    if (!infile) 
    { 
     cout << "Cannot open input file! Program aborted" << endl; 
     return 1; 
    } 

    outfile.open("C:\\Users\\Arctic-Gaming\\CLionProjects\\working\\Source\\Binary Conversion (Loop w File)\\Decimal Output.txt"); //connect the stream to an actual file 

    do 
    { 
     int remainder [15] = {0}; 
     remainder_count = 15; 

     infile >> num; 
     outfile << "\n" << num << endl; 
     if (num > 0 && num <= 65535) 
     { 
      while (num > 0) 
      { 
       remainder[remainder_count] = num % 2; 
       num /= 2; 
       remainder_count--; 
      } 

      remainder_count = 0; 
      while (remainder_count < 16) 
      { 
       if (remainder_count % 4 == 0) 
       { 
        outfile << " "; 
       } 
       outfile << remainder[remainder_count]; 
       remainder_count++; 
      } 
     } 
     else if (num == 0) 
      outfile << "0000 0000 0000 0000" << endl; 

     else 
      cout << "Error! Invalid Input." << endl; 
    } 
    while (!infile.eof()); 
} 
+4

'remaining [remainder_count]' - 如果'remaining_count == 15'怎麼辦?看到那條線有什麼問題? – PaulMcKenzie

+1

歡迎使用堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+1

解決這些問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

回答

1

程序具有不確定的行爲。由於行爲未定義,因此使用std::cout與使用文件流相反無關。

int remainder [15] = {0}; 
//... 
remainder_count = 15; 
//... 
remainder[remainder_count] = num % 2; // out-of-bounds access (remainder[15] is out-of-bounds) 

一旦上面這一行被執行,所有的投注都關閉,關於你的程序如何表現。數組範圍從0n-1的有效索引,其中n是數組中元素的數量。因此,有效索引是0,1,2,對於remainder陣列最高爲14

如果您已經切換到使用std::array而不是常規C++陣列,而不是不確定的行爲,你會得到一個std::out_of_range例外,因爲您訪問使用at()該元素儘快拋出。

 std::array<int, 15> remainder= {{0}}; 
    remainder_count = 15; 
    //...  
    if (num > 0 && num <= 65535) 
    { 
     while (num > 0) 
     { 
      remainder.at(remainder_count) = num % 2; //... exception thrown 

Live Example

所以你看,你的程序從來沒有像你所宣稱的「運行良好」,你將不得不修改你的程序,讓你不會出界外的數組。

+0

感謝您的陣列提示。我不知道我錯了。當我創建數組時,我認爲數字是我想要的元素數量,從0開始到15結束。這將是16個總數。只要將我的數組更改爲這樣就可以修復它:'array remaining;' –