Outfile会导致内存冲突崩溃

时间:2017-03-12 11:39:32

标签: c++ arrays fstream access-violation

我正在编写一个将数字从十进制转换为二进制的程序。我已经有了正确的算法,并且程序在使用cout时工作正常。但是,只要我在循环中使用outfile,程序就会崩溃并显示错误代码(0xC0000005)。 这是我的源代码:

#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());
}   

1 个答案:

答案 0 :(得分: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是数组中元素的数量。因此有效索引为01214数组最高为remainder

如果您已切换到使用std::array而不是常规C++数组,而不是使用未定义的行为,则只要使用{{{{}}访问该元素,就会抛出std::out_of_range异常1}}。

at()

Live Example

所以如你所见,你的节目从来没有“好运”#34;正如你声称的那样,你将不得不修改你的程序,这样你就不会超出阵列的范围。

相关问题