access violation stack overflow c++

-1

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?

c++
stack
overflow
asked on Stack Overflow Oct 28, 2018 by user7295833

2 Answers

2

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.

answered on Stack Overflow Oct 28, 2018 by eerorika
0

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)

answered on Stack Overflow Oct 28, 2018 by OznOg

User contributions licensed under CC BY-SA 3.0