[MINC-users] dynamic memory allocation for hyperslabs

Andrew Janke a.janke at gmail.com
Wed Apr 27 19:11:26 EDT 2011


Hi Thomas,

On Thu, Apr 28, 2011 at 05:59, Thomas Funck <thomas.funck at mail.mcgill.ca> wrote:
> I'm trying to dynamically allocate memory for a hyperslab, but this always seems to lead to a seg fault.  I used hyper-test.c to try and figure out the problem. The normal hyper-test.c compiles and runs fine, so I changed "dtemp[CX][CY][CZ];" to "double ***dtemp;" and then allocate the necessary memory by doing:
>
>        dtemp=malloc(CX * sizeof(double**));
>        for(i=0; i< CX; i++)
>        {
>        dtemp[i]=malloc(CY * sizeof(double*));
>                for(j=0; j < CY; j++)
>                {
>                dtemp[i][j]=malloc(CZ * sizeof(double) );
>                }
>        }
>
> However this resulted in a seg fault on the line:
>
> if (fabs(r - dtemp[i][j][k]) > 1.0e-15)
>
> So even though "miget_real_value_hyperslab" returns 0 and says it gets the hyperslab correctly, there seems to be a problem dereferencing "dtemp" when the memory has been dynamically allocated.
>
> Is there something wrong with my C? Or does "miget_real_value_hyperslab" not work correctly for dynamically allocated memory?

miget_real_value_hyperslab does work for dynamically allocated memory,
but I dont think you are doing what you want to be...
miget_real_value_hyperslab is expecting a pointer to a memory buffer
that will be then indexed as per a "normal" multidimensional array.
see:

   http://pw1.netcom.com/~tjensen/ptr/ch7x.htm

or

   http://en.wikibooks.org/wiki/C_Programming/Arrays

for an explanation of how in C array[x][y] is really just *(*(array + x) + y)

What you are allocating is an array of pointers to arrays pointers to
arrays.  (Here's hoping I got my grammar right there!). If you want to
dynamically allocate the array you can either do a single malloc

   buf = malloc(sizeof(double) * CX * CY * CZ)

or take advantage of being able to declare arrays within blocks:

   int somefunction(int CX, int CY, int CZ){
      array[CX][CY][CZ];

      ...

   }

The reason your array of pointers to arrays or pointers to arrays
doesn't work as you'd expect is that miget_real_value_hyperslab will
be attempting to stuff the entire hyperslabs values into the first
array of pointers (ie: in dtemp), which is nothing more than array of
double* of length CX. Odds are this will work at runtime as C doesn't
do much bounds checking and odds are the memory you are allocating for
the sub-arrays will be right after dtemp so things will probably work
90% of the time. When you go to access the elements though things may
well break.

Hope that helps, I could be wrong with the above but this is what I
can guess from the code and info you have sent so far.

ta


-- 
Andrew Janke
(a.janke at gmail.com || http://a.janke.googlepages.com/)
Brisbane->Australia    +61 (402) 700 883


More information about the MINC-users mailing list