When you do
newBoard[0] = (int *) malloc(sizeof(int) * cols * rows);
you are allocating a continous block of memory for cols * rows
spaces of int
objects.
You can only free it once using the start of the block, you cannot free it at an
offset of the start of the memory and you cannot free it multiple times, only
once.
for (i = 0; i < rows; i++) {
newBoard[i] = (*newBoard + cols * i);
}
Here the newBoard[i]
are getting an offset of the continues block of memory,
so you cannot free more than once at different offsets, you have to free it
once at the start of the block.
free(newBoard[0]);
free(newBoard);
would be correct.
Please don't cast malloc
, this is bad practice. And you should check if
malloc
returns NULL
.
I personally think that this is a clever way to do only 2 malloc
s instead of
row+1
malloc
s, but it has downsides, too. You have to be very careful with it. Freeing single blocks of memory that
are not needed is not possible, reallocation of single newBoard[i]
is also not
possible. You have to have a lot of discipline in order to avoid mistakes like
multiple free
s, that's why I think that the traditional way of doing, is
better overall. I'd do:
for(i = 0; i < rows; ++i)
newBoard[i] = malloc(cols * sizeof *newBoard[i]);
then you can free like you did.