Your
struct Species has five members of size
sizeof(double) * SIZE
. For an X86 system that works out to about 38 MB of data when SIZE = 1,000,000. That means that for every
struct Species you declare, you are using that much space
on the stack.
I can think of 4 options:
1) modify your run-time environment to provide a larger stack
2) If you only have one instance of
struct Species
, you might consider declaring it globally. There's a whole lot of literature about global variables and when, where, why or why-not, so you should look into that before deciding to go that route
3) allocate on the heap e.g.
struct Species *s;
s = malloc(sizeof *s);
4) you have a member variable
species.num
. This seems to be the actual number of items you're tracking. If that's read in from somewhere, e.g a database or file, then you can minimize your memory use my allocating the large arrays individually e.g.
typedef struct Species {
double *x;
double *y;
double *vx;
double *vy;
double *vz;
size_t num; ...
}species;
...
int main()
{
species sp;
sp.num = get_num_particles(); sp.x = malloc(num * sizeof *sp.x);
sp.y = malloc(num *sizeof *sp.y);
...
sp.vz = malloc(num *sizeof *sp.z);
free(sp.x);
free(sp.y);
....
free(sp.vz);
return 0;
}
Note that we're not using
sp.x = malloc(num * sizeof(double)
to allocate memory. By using
sp.x = malloc(num * sizeof *sp.x)
, if we change the type of sp.x to e.g.
long double
, we don't then need to go and find all the places we alloc() sp.x and make sure the type agrees, that's handled for us by the compiler.