Hello all, I'm a physicist whose rewriting a numerical simulation,
previously written in IDL, in C with the goal reducing runtime. As you
may imagine, my C programming skills are quite poor but I am learning.
My problem is this. I had sucessfully written a C code that worked
( with considerable speedup over the IDL version ) using an array size
of 100x100. However, I am working towards making the array size closer
to 300x300. Since I had defined 2D arrays in my code as
double array[nCols][nRows];
upon increasing nRows above approximately 250 with nCols = 100 the
program was segfaulting. After some reading I came to the conclusion
that I was creating arrays that were too big for the stack and should
instead be allocated memory on the heap? It's quite possible that i'm
very wrong here so please point out my mistakes. To allocate space on
the heap for the arrays, and for conveniance in array indexing, I
chose to replace the static array creation lines with a malloc call
like (found in the cfaq)
double **array = malloc ( nCols * sizeof ( *array ) );
array[0] = malloc ( nCols * nRows * sizeof ( **array ) );
for ( ii = 1; ii < nCols; ++ii )
array[ii] = array[0] + ii * nRows;
such that indexing the array may be done according to
for ( ii = 0; ii < nCols; ++ii )
{
for ( jj = 0; jj < nRows; ++jj)
{
array[ii][jj] = 0.0;
}
}
Now this also appeared to work. Upon altering the code to use the
malloc statement instead of the static [][] approach I tested the
outputs of the simultaion. They were fine up to a point where I had
converted most of the static array creation lines to the malloc method
above. However, trying to convert more caused a problem. Irrelevant of
which additional array I tried to allocate space for on the heap, the
simulation results would become rubbish. It does not appear to be a
problem with the simulation itself, since the problem occurs with
small array sizes as well which work fine using a static array
declaration, but rather with my poor attempt at memory management in
C. So my questions are:
1. Are arrays of size 300x300 large enough to overwhelm the space
available on the stack (if relevant my machine is an Intel Core 2 Duo
running linux)?
2. What is the standard approach to creating large 2D arrays, i.e., is
the approach I have chosen appropriate?
3. Is it possible I have allocated too many 2D arrays (perhaps 30 in
all) using the above malloc approach and that is the cause of my
simulation woes?
Any help would be great as my brain is slowly melting away.
Dav.