I’m trying to learn C and I’ve gotten to a point where I felt like trying something more advanced than small and easy examples of printing text to the console, using pointers in a very simple way and so on.
The problem is that my program crashes on my call to free and I’m sure it is the pointer(s) somehow haunting me…
So, I have created a two-dimensional array like this:
bool InitializeGrid(struct Grid *g, int rows, int columns)
{
g->rows = rows;
g->columns = columns;
g->grid = malloc(g->rows * sizeof(int *));
if(g->grid == NULL)
{
printf("Could not allocate memory for grid rows.\n");
return false;
}
for (int i = 0; i < g->rows; i++)
{
g->grid[i] = malloc(g->columns * sizeof(int));
if(g->grid[i] == NULL)
{
printf("Could not allocate memory for grid columns.\n");
return false;
}
}
/ ... /
return true;
}
The structure Grid looks like this:
struct Grid
{
int rows;
int columns;
int **grid;
};
I then successfully use the grid throughout the program and everything works great. When the program is about to exit, I need/want to free the memory I allocated. This is how I do that:
void CleanupGrid(struct Grid *g)
{
for(int i = 0; i < g->rows; i++)
free(g->grid[i]);
free(g->grid);
}
But on the first free(g->grid[i]) I receive a segmentation fault.
Why does this not work? How can I fix this?
Edit:
stdbool.h has been included in the program for use of bool/true/false.
I feel really stupid for staring blind at the free() statement. When I scale down the program to the absolute minimum, it works great with the free() statements. It is when I access and write to the grid at one point that the free() greets me with a segmentation fault.
Accepting user1083265’s answer.
I compile your code (just alloc/dealloc) and it doesn’t crash.
Possibly, when using allocated grid, you corrupt some memory above allocated fragments. Glibc uses canary values to detect such corruption – so you get segfault when freeing corrupted memory.