Freeing dynamically allocated memory
I found this code on the internet. Its purpose is to allocate a contiguous memory block for a two-dimensional dynamic array.
Code:
int** x;
int* temp;
x = (int**)malloc(dimension1_max * sizeof(int*));
temp = (int*)malloc(dimension1_max * dimension2_max * sizeof(int));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}
How should I free the memory allocated with such code?
I'd go for:
Code:
free(x[0]);
free(x);
Is my assumption correct? I also think I can "forget" the temp pointer because it points to the same memory block as x[0].