[MINC-users] dynamic memory allocation for hyperslabs
Simon Eskildsen
eskild at gmail.com
Wed Apr 27 16:24:52 EDT 2011
Hi Thomas,
If you want to dynamically allocate a 3D array, I would recommend
doing something like the code below to avoid multiple allocations in
for loops. Not sure if it solves your problem though.
Best,
Simon
dtemp = alloc_3d_double(CX, CY, CZ);
...given the function:
double ***alloc_3d_double(int n1, int n2, int n3)
{
double ***iii, **ii, *i;
int j;
iii = (double ***) calloc(n1,sizeof(double **));
alloc_error_check(iii);
ii = (double **) calloc(n1 * n2,sizeof(double *));
alloc_error_check(ii);
iii[0] = ii;
for (j = 1; j < n1; j++) {
iii[j] = iii[j - 1] + n2;
}
i = (double *) calloc(n1 * n2 * n3,sizeof(double));
alloc_error_check(i);
ii[0] = i;
for (j = 1; j < n1 * n2; j++) {
ii[j] = ii[j - 1] + n3;
}
return iii;
}
...and the definition:
#define alloc_error_check(p) { \
if ((p) == NULL) { \
fprintf(stderr, "ERROR! Allocation failure. Probably out of
memory.\n"); \
exit(1); \
} \
}
On Wed, Apr 27, 2011 at 3:59 PM, Thomas Funck
<thomas.funck at mail.mcgill.ca> wrote:
> Hi,
>
> 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?
>
> Many thanks for any help!
>
> Best,
>
> Thomas
> _______________________________________________
> MINC-users at bic.mni.mcgill.ca
> http://www.bic.mni.mcgill.ca/mailman/listinfo/minc-users
>
More information about the MINC-users
mailing list