0

I am developing a code in which there is need for declaring array of double of size 150000 and when one array is declared code is running successfully.if we declare two arrays then while execution it terminates throwing exception.

Code is :

double a[150000];
double b[150000];

if we declare a only then it executes perfectly.if declare both a and b then it terminates. Can anyone suggest how to resolve this?

Jasdeep Singh Arora
  • 543
  • 2
  • 11
  • 31

3 Answers3

6

The two arrays are overflowing the stack (assuming they are local variables). Dynamically allocate memory for the arrays instead, using a std::vector to manage the memory for you:

std::vector<double> a(150000);
std::vector<double> b(150000);

Even though the std::vector instances are on the stack, the std::vector dynamically allocates memory internally for the data which is on the heap, avoiding the stack overflow.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • This is good, but worth mentioning that in C++03 it's unavoidably slower initially as all elements are written to when the vector is created. – Tony Delroy Apr 25 '13 at 11:25
  • 1
    @TonyD: That is just 2M of data, the cost of initialization is most probably negligible. If that is an issue, there are alternatives, but most probably the arrays are meant to be used, in which case most of the cost of initialization (actually touching the memory addresses) have to be paid anyways... – David Rodríguez - dribeas Apr 25 '13 at 11:29
4

Okay! You have Stack Overflow in your app! enter image description here

Fixing examples:

  • don't use stack - use dynamic memory allocation (heap):

    double* a = new double[150000];

  • use STL container, for example, vector - internally it allocates things on heap

    std::vector<double> a(150000);

  • increase stack size (bad idea, but if you really need it read you compiler docs, and look here)

  • redesign you code somehow
Community
  • 1
  • 1
Ivan Aksamentov - Drop
  • 12,860
  • 3
  • 34
  • 61
2

There is one solution to this problem, but it leads to (at least) three different follow-on solutions. The solution is "don't use large arrays as local variables, because it blows up the stack".

The solution clearly means changing the code in some way. There are a few different ways to do that.

The obvious and straight-forwards solution is to use std::vector<double> instead.

Another solution is to use `

unique_ptr<double[]> a = std::unique_ptr<double[]>(new double[150000]);

The third, and SOMETIMES a good solutions, is to make a and b global variables.

There are several other variants, but they are generally variations on the same theme, just with slight variations. What is best in your case really depends on what the rest of your code is doing. I'd start with std::vector<double>, but other alternatives do exist, should that be an unsuitable solution for some reason.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227