Hi all,

I'm trying to allocate a tensor, but I seem to be having some difficulties with it, so I was hoping someone could point out my error to me. Here is my code

Code:

u_ssint ***u_ssint_tensor(int rows, int cols, int depth)
/* creates a memory structure of type u_ssint, which is an unsigned char */
{
int i, j;
// check input
if (rows < 0)
{
printf("rows must be >= 1, rows = %d in u_ssint_tensor\n", rows);
printf("exiting\n");
exit(-1);
}
if (cols < 0)
{
printf("cols must be >= 1, cols = %d in u_ssint_tensor\n", cols);
printf("exiting\n");
exit(-1);
}
if (depth < 0)
{
printf("depth must be >= 1, cols = %d in u_ssint_tensor\n", depth);
printf("exiting\n");
exit(-1);
}
u_ssint ***usi;
// first create a vector of size cols of type u_ssint**
usi= calloc(cols, sizeof(u_ssint **));
if (usi==NULL)
{
printf("could not allocate memory for columns in u_ssint_tensor\nexiting\n");
exit(-1);
}
for (i= 0; i < rows; i++)
{
usi[i]= calloc(rows, sizeof(u_ssint *));
if (usi[i]==NULL)
{
printf("could not allocate mmeory for row %d in u_ssint_tensor\nexiting\n", i);
exit(-1);
}
for (j= 0; j < depth; j++)
{
usi[i][j]= calloc(depth, sizeof(u_ssint));
if (usi[i][j]==NULL)
{
printf("could not allocate mmeory for row %d, depth %d in u_ssint_tensor\nexiting\n", i, j);
exit(-1);
}
}
}
return usi;
}

That doesn't produce any errors, but when I try to go through the created tensor, I get an EXC_ACCESS error

e.g.

Code:

int j, k, l;
usi= u_ssint_tensor(1000, 1000, 20);
usi= u_ssint_tensor(1000, 1000, 20);
for (j= 0; j < 1000; j++)
{
for (k= 0; k < 1000; k++)
{
for (l= 0; l < 20; l++)
{
printf("j= %d, k= %d, l= %d\n", j, k, l);
usi[j][j][l]= 1;
}
}
}

the program ends up bailing at:

Code:

j= 19, k= 999, l= 18
j= 19, k= 999, l= 19
j= 20, k= 0, l= 0

Also- note that if I change the dimensions of the tensor from 1000,1000,20 to 1000,1000,15, then instead of the program bailing at j=20, k=0, l=0, it bails at j=15, k=0, l=0, which makes me think I'm accidentaly not allocating enough memory for the first dimension- and that somehow it's 15, and not 1000.

If anyone could provide some assistance, I'd greatly appreciate it!

Cheers,

Brad