0

I need to create an array like this

double grid [15000][40];

but the stack in Visual Studio 2012 is only of 1MB. How can I use variables like this or bigger? This mean that if I create a

std::vector<int>

and I push_back 600 000 times it goes in stack overflow? This seems a big limitation, how can be solved? Thank you in advance.

Nisba
  • 3,210
  • 2
  • 27
  • 46

5 Answers5

3

Large objects should have either static or dynamic storage duration.

Static:

int a[1000000];

void f()
{
    a[3] = 12;    // fine
}

Beware of shared, concurrent accesses to the static memory, though.

Dynamic (but managed properly by a suitable class):

void f()
{
    std::vector<int> a(1000000);   // dynamic objects managed by std::vector
    a[3] = 12;
}

Here each function call will create and manage its own dynamic allocation (and the complexities of concurrency are delegated to the memory allocator, so you don't have to think about those).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

There is no problem here.

This mean that if I create a std::vector and I push_back 600 000 times it goes in stack overflow? This seems a big limitation

No, because vectors elements do not have automatic storage duration (they don't "live on the stack"). They couldn't.

how can be solved

There is nothing to solve. Vector elements are dynamically allocated.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

You can define this array as

static double grid [15000][40];

As for std::vector then it allocates memory for its elements in the heap not in the stack.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

memory of vector is heap allocated, you don't have to worry about the stack. Instead of doing push_back, you can use the member function resize :

 std::vector<int> grid;
 grid.resize(15000*40);

or even better, you can use a unique pointer if the grid has a fixed size

pan-
  • 143
  • 9
0

If you don't want to use std::vector for whatever reason, an alternative solution is:

int main()
{
  int (*grid)[40] = new int[15000][40];

  // work with grid
  grid[0][0] = 0.0;
  grid[14999][39] = 42;

  delete [] grid;
}

The usual caveats apply about raw pointers to dynamic storage causing memory leaks if the scope is terminated by an exception, so that the delete never executes.

Kaz
  • 55,781
  • 9
  • 100
  • 149