Reputation: 13
When I run the following code I get a stack overflow. How is it possible? I thought if I define an array outside of main it will be static and I won't have memory problems? What can I do against it?
#include <stdio.h>
#define dim1 14001
#define dim2 14001
#define dim4 8
double large_array[dim1][dim2][dim4];
int main()
{
large_array[30][6][5] = 1337;
printf("%lf\t",large_array[30][6][5]);
}
Upvotes: 1
Views: 378
Reputation: 49180
3-D global array you declared consumes too much memory (~1043456KB.i.e..~1GB) on heap
while initialising at compile time, which is why your program is giving overflow problem.
One intuitive way to handle this problem is to use multidimensional map
STL instead of Multidimensional Global array.
#include<stdio.h>
#include<map>
/*#define dim1 14001
#define dim2 14001
#define dim4 8
double large_array[dim1][dim2][dim4];
*/
using namespace std;
map<double, map<double,map<double,double> > > large_array;
int main()
{
large_array[30][6][5] = 1337;
printf("%lf\t",large_array[30][6][5]);
}
Upvotes: 0
Reputation: 1433
The maximum size of an statically allocated array is determined by the amount of memory that a program can access. On a 32-bit system, the maximum amount of memory that can be addressed by a pointer is 2^32 bytes which is 4 gigabytes. The actual limit may be less, depending on operating system implementation details and compiler implementation choices.
As interjay said in comment, your allocation requires quite higher amount of space.
In C++, you should use the provided containers like vector or the boost multi dimensional arrays to handle such cases.
Upvotes: 0
Reputation:
One problem this has is that it's very likely that the place where the compiler wants to store the array doesn't have room to fit that much memory -- in some environments, very large allocations must be done on the heap, e.g. with malloc
, new
, or other similar means (or implicitly through those means, e.g. as done internally by std::vector
).
Upvotes: 2