The following is my code and I cannot figure out where I am going wrong to free my 2d array. I know that the error happens at this line: free(arr[i]); and I also know that I have to do this loop to free each integer before freeing the entire array later. Can anyone spot the bug here? I get no compilation errors, but once running my executable, there is a huge backtrace output for the free function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int h = 4;
int w = 2;
int i, j;
int **arr = (int**)malloc(sizeof(int*) * h);
arr[0] = (int*)malloc(sizeof(int) * w * h);
for (i=1; i<h; i++)
{
arr[i] = arr[0] + (w*i);
}
int count = 0;
for (i=0; i<h; i++)
{
for (j=0; j<w; j++)
{
arr[i][j] = count++;
}
}
for (i=0; i<h; i++)
{
for (j=0; j<w; j++)
{
printf("Array[%d][%d] = %d ", i, j, arr[i][j]);
}
printf("\n");
}
for (i=0; i<h; i++)
{
free(arr[i]);
}
free(arr);
/*printf("\nAfter freeing the array it becomes:\n");
for (i=0; i<h; i++)
{
for (j=0; j<w; j++)
{
printf("Array[%d][%d] = %d ", i, j, arr[i][j]);
}
printf("\n");
}*/
}