Hi,
This maybe a stupid question, but here goes. I just want to see how free and NULL would work with a pointer to pointer, so I have this code:
Code:
void free_array(int ** ptptArr, int m)
{
for ( int i = m ; i >= 0; i--)
{
free(ptptArr[i]);
ptptArr[i] = 0;
printf("set ptptArr[%2d] = NULL.\n",i);
}
putchar('\n');
free(ptptArr);
ptptArr = 0;
if(ptptArr == NULL) printf("set **ptptArr to NULL.\n");
}
Then, in main, I have:
Code:
// ut is type int **
free_array(ut,n);
printf("After free.\n\n");
for(int k = 0; k < n; k++)
{
ut[k] == 0 ? printf("ut[%d] = Null\n",k) : printf("ut[%d] != Null\n",k);
}
ut == NULL ? printf("**ut = NULL.\n") : printf("**ut != Null.\n");
for (int i=0;i<n;i++)
{
printf("%d ",i);
for(int j= 0;j<n;j++)
printf("%2d ", ut[i][j]);
putchar('\n');
}
So i thought it's supposed to set all the pointer "ut[k]" to null, and "ut" to null as well. After compiled and run, I get:
Code:
After free.
ut[0] != Null
ut[1] = Null
ut[2] = Null
ut[3] = Null
ut[4] = Null
ut[5] = Null
ut[6] = Null
ut[7] = Null
ut[8] = Null
ut[9] = Null
**ut != Null.
0 0 49 135696480 1 2 3 4 5 6 7
Segmentation fault
.
I thought that "ut" is set to null, but it's not. Why does that function not work?
However, if i don't use the function to free, and do all the free-up and setting to NULL in main:
Code:
for ( int i = n ; i >= 0; i--)
{
free(ut[i]);
ut[i] = 0;
printf("set ptptArr[%2d] = NULL.\n",i);
}
ut = 0;
printf("After free.\n\n");
ut == NULL ? printf("**ut = NULL.\n") : printf("**ut != Null.\n");
for(int k = 0; k < n; k++)
{
ut[k] == 0 ? printf("ut[%d] = Null\n",k) : printf("ut[%d] != Null\n",k);
}
for (int i=0;i<n;i++)
{
printf("%d ",i);
for(int j= 0;j<n;j++)
printf("%2d ", ut[i][j]);
putchar('\n');
}
Then, "ut" is set to NULL, and I can't access it anymore:
Code:
**ut = NULL.
Segmentation fault