Currently, I'm learning about pointers and static/dynamic memory allocation. In the following code, I have a 3D array. The variable array is a pointer to a pointer to a pointer mat3***
. I've learnt that malloc
allocates memory from the heap and returns a pointer. The function free
frees that memory.
int main()
{
double*** mat3;
int m,n,p;
int i,j,k;
m=2; n=3; p=4; /* unequal dimensions should work fine as well */
mat3 = (double***) malloc(m*sizeof(double**));
if (mat3 == NULL)
exit(1);
for (i=0; i<m; i++)
{
mat3[i] = (double**) malloc(n*sizeof(double*));;
if (mat3[i] == NULL)
exit(1);
for (j=0; j<n; j++)
{
mat3[i][j] = (double*) malloc(p*sizeof(double));
if (mat3[i][j] == NULL)
exit(1);
}
}
// Fill with some data that makes checking easy (value = sum of the indexes) :
for(i=0;i<m;i++)
for(j=0;j<n;j++)
for(k=0;k<p;k++)
mat3[i][j][k] = i + 10*j + 100*k;
show(mat3,m,n,p);
free(mat3);
}
So after showing I'm done with the 3D array and I want to free the memory. Therefore I use free
, but I really doubt if I did it correctly. Since I gave to command for the ***
to be freed, but the **
itself and the *
were not in a command. So that would mean that in the heap there are still pointers to pointers and the pointers itself. If that is true I wouldn't know how to free the memory, maybe I could use the same loop, but then instead of allocating memory I could free it.
Another question is more theoretical. Since I freed the memory, but the memory is not overwritten immediately. If I use free()
before printf()
I get a segmentation error. Although the memory is freed? The physical memory location still exists right? So why couldn't I access it with the reference address?