Can you explain where and how the code for freeing the dynamically allocated memory in the code below is wrong?
This is the code to initialize, print, and release a two-dimensional array through memory dynamic allocation.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main() {
int idx, row, col, x, y;
int **pptr = (int **)malloc(sizeof(int *) * 8);
if (NULL == pptr) {
printf("ERROR: malloc failed.\n");
exit(1);
}
for (idx = 0; idx < 8; idx++) {
*(pptr + idx) = (int*)malloc(sizeof(int) * 6);
if (NULL == *(pptr + idx)) {
printf("ERROR: malloc failed.\n");
exit(1);
}
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 6; col++) {
*(*(pptr + row) + col) = 6 * row + col;
}
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 6; col++) {
printf("%3d", *(*(pptr + row) + col));
}
printf("\n");
}
for (idx = 0; idx < 8; idx++) {
free(*(pptr + idx));
if (NULL != *(pptr + idx)) {
*(pptr + idx) = NULL;
}
}
free(pptr);
if (NULL != pptr) {
pptr = NULL;
}
return 0;
}
If something is wrong, how can I fix it?