I am trying to create an array of a object Cell in main
function,
int nc=26 730 899;
Cell c[nc];
and Cell is a object which I am constructing with no arguments in.
// Constructor
Cell::Cell(){};
when nc
is relatively low it works fine. The problem is when it takes big numbers, like the one in example, where it compiles, but retrieves a bad access error.
Does it mean my computer has no further memory, what kind of memory is this and how can work around this issue?
I am trying to develop a program to run computational fluid dynamics problems using finite volumes method, where each cell is an object so I will need tones of cells!
In the example (3D) I am just trying 299 cells in x by 299 in y by 299 in z = 26 730 899
, which is very short yet.
Maybe my approach is being performed the wrong way!?
I am completely new to c++, so keep it as simple as possible, pleaseee. :)
Thank you all.
Note: I don't know if is it relevant, but I am running the code in Xcode on a MacBookPro from 2010.
Does it mean my computer has no further memory,
Your compiler, unless told otherwise, produces executable programs in which the total size of objects with what the C++ language calls automatic storage duration is limited in a way that makes sense for the operating system on which the program should run.
You haven't shown your full code, but your array apparently has automatic storage duration.
Now, C++ automatic storage duration is usually implemented with something called the stack. How that stack works, how it is limited and how you can change those limits for your program is all implementation-specific.
What matters here is that you just shouldn't create huge objects with automatic storage duration. It's not made for that purpose.
and how can work around this issue?
Use dynamic storage duration and put the objects on the free store with std::vector
:
int nc = 26730899;
std::vector<Cell> c(nc);
[*] Your code is also using a non-portable GCC extension, because in standard C++, an array's size must be fixed at compile time, but that doesn't matter much for the problem at hand; you'd probably get the same error if nc
was const
.