YuZ
YuZ

Reputation: 445

unable to initialize double array

I have 4 gig RAM and the following lines that throws a stackoverflow exception:

int main()
{
     double X[4096*512], Y[4096*512], Z[4096*512];
     return 0;
}

each double takes 8 bytes space, so my three arrays should be 3*4096*512*8/1024/1024 = 48 Mbyte big, can somebody explain the error or is 48 Mbyte too much to handle?

Upvotes: 0

Views: 127

Answers (3)

IdeaHat
IdeaHat

Reputation: 7881

Expanding my comment (not a thorough description, you should do more research), there are two types of memory, the "stack" and the "heap". The stack is the local working memory of a piece of software, while the heap is the big pool. The stack holds all the local variables of a function call. Anything local declared within the function will be stored on the stack. The stack had a nifty property that it can be "pushed": when we call the next function, we go further down the stack and start over. But this means that the amount of stack memory needs to be generally reserved for the lifetime of a program, so we limit it to a small amount: general 1 to a few megabytes.

When you run out of stack memory, you get a "Stack Overflow" ("Now thats what that means!")

The heap is kindof the rest of the memory. The heap is where the program stores any dynamic memory and (possibly, it can be more complicated) global variables. The heap is where things like malloc and new puts its memory.

Whenever you declare a local variable, it is stored on the stack. This isn't a problem for small variables, but arrays like the ones you have get HUGE easy.

If you don't want to worry about new or malloc you can use things like std::vector, which will put the large amount of data on the heap while giving you local variable semantics.

Again, this is "basic programming" so you should get really familiar with this subject.

Upvotes: 0

Mike Ounsworth
Mike Ounsworth

Reputation: 2504

If you want to avoid the overhead of std::vector, you can allocate the arrays on the heap

double *myArray = new double[SIZE];

and remember to free them.

delete [] myArray;

Upvotes: 0

NetVipeC
NetVipeC

Reputation: 4432

You are declaring in the stack, normally the stack in OS are limited (eg: 1MB), you could expanded when compiling (eg: in GCC use -Wl,stack_size,134217728 128Mb) but don't recommend.

Better use std::vector<double>.

#include <vector>

int main() {
     std::vector<double> X(4096*512), Y(4096*512), Z(4096*512);
     return 0;
}

Upvotes: 1

Related Questions