Hi all, I've been having a seg fault problem that depends on the size of my an array whose dimension are specified using #define. E.g.
1 2 3
#define NX 25
#define NY 25
#define NZ 25
The array in question is actually an array of structs;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// holds all info about a single grid point
struct GridPoint
{
double Metric[3][3];
double Kcurv[3][3];
double invMetric[3][3];
double dMetric[3][3][3];
double Gamma[3][3][3];
double dGamma[3][3][3][3];
};
// holds info about the whole grid
struct Grid
{
GridPoint P[NX][NY][NZ];
};
I have another class that has one of the above structures as a member, so
1 2 3 4 5 6
class Disc
{
...
Grid grid;
...
};
If the defines arrays numbers are not to big, there are no problems. But at the values shown, I get a segfault at the point where I instantiate an object of the Disc class. Now, the actually memory usage is not too big, I can allocate much bigger chunks of memory using 'new', but for various reasons using #define is preferably in this project.
Is there some hard limit on the size of memory given to hardcoded sized objects in this way? Of course there are many other things that could really be behind the segfault, but the code works fine as long as those numbers are small (and uses only moderate amounts of memory) and just segfaults immediately if they are too high.
You are asking too much to the stack, the size of 'Grid' would be
( 3*3 + 3*3 + 3*3 + 3*3*3 + 3*3*3 + 3*3*3 ) * 25 * 25 *25 * sizeof(double) which ( assuming sizeof(double) == 8 ) is equal to 108,000,000 bytes
Use something as deques instead of arrays, so you won't need all this contiguous memory
Thanks Bazzy, that explains the problem. However my knowledge of the actual mechanics of memory allocation is sorely lacking, so let me clarify if I may. Where and how is memory allocated when you use dynamic memory (with new or malloc) as opposed to hardcoded memory (I don't know what deques means..)? This sounds like I've got a fundamental gap in knowledge here, so any good intro's to this might be a good place to direct me if anyone has a good link?
A deque is a C++ standard container: http://www.cplusplus.com/reference/stl/deque/
As class class objects, a deque may use more memory than an array but it doesn't need all it's members to me in a single chunk of memory
Using memory on the heap ( allocated with new and malloc ) is more flexible than the stack ( automatic memory ) but it will use for single arrays and objects a contiguous part of memory too