Hello,
I just discovered something that left me wondering what I had actually understood about dynamic allocation of memory. Let's say I have the following trivial example:
Code:
int **array, i, j, nrows=10, ncolumns=20;
array = malloc ( nrows * sizeof(int *) );
for ( i = 0; i < nrows; i++ ) array[i] = malloc ( ncolumns * sizeof(int) );
for ( i = 0; i < nrows; i++ )
{
for ( j = 0; j < ncolumns; j++ )
{
array[i][j] = i*j;
printf("%d %d %d\n",i,j,array[i][j]);
}
}
This, of course, compiles and runs as expected.
If I now change the last part to
Code:
for ( i = 0; i < nrows+1; i++ )
{
for ( j = 0; j < ncolumns; j++ )
{
array[i][j] = i*j;
printf("%d %d %d\n",i,j,array[i][j]);
}
}
I get a bus error when I run it, at the expected place (i=nrows+1). Good (I think?)
If instead I do
Code:
for ( i = 0; i < nrows; i++ )
{
for ( j = 0; j < ncolumns+1; j++ )
{
array[i][j] = i*j;
printf("%d %d %d\n",i,j,array[i][j]);
}
}
The code compiles and runs happily. Indeed, I can go up to 10000*ncolumns or so, and the thing does not complain?!?!?!?!? (after some big number there is a segmentation fault)
What am I actually doing with malloc? I am using gcc on OSX (Leopard)
Thanks for any enlightenment,
mc61