简体   繁体   中英

access violation stack overflow c++

every one...

I am very new in C++... My problem is about reading a big text file in C++ visual studio 2012...

Here is my simple code:

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main() {
    double x;
    int i,j;
    ifstream inFile;
    i=0;
    j=0;



 double x_array[800050][1] ;

    x = 0;
    inFile.open("D:\\a.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    while (inFile >> x) {

                         x_array[i][0]=x;
                         i++;

    }

    inFile.close();
    return 0;
}

But when I debug the code, I am encountered with this error:

Unhandled exception at 0x01242327 in textreader.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00E42000).

When I reduce the size of the input text file (decreasing the input number), the problem is solved... But I need the entire of the input text file...

What should I do? The problem is in the code or I should find a better way?

Automatic variables are typically placed on the call stack. The default size of the call stack on most desktop systems is from one to a few megabytes. The size of double [800050][1] is over six megabytes (assuming the size double is eight bytes). The result of using such a huge automatic variable results in a stack overflow , as you have observed.

Don't use automatic variables for large objects. You can allocate the object dynamically instead. In this case, you can use std::vector<double> .

Another issue is that you've hard coded the size of the array, and therefore you risk overflowing the array even if it did fit on the stack. When you use std::vector , you can let it grow dynamically instead of hard coding the size.

you are (as mentioned in error) doing a stack overflow when allocating:

  double x_array[800050][1] ;

you should try to allocate it on the heap (directly using new, or indirectly using a std container like std::vector)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM