This is my code to allocate memory using malloc for a 2 dimensional array in C, and to free it. N is a number given by the user
R = malloc(N * sizeof(int *)); // start of memory allocating for **R
if (R == NULL) {
return -1;
}
for (i = 0; i <= N; i++) {
*(R+i) = malloc(N * sizeof(int));
if (*(R + i) == NULL) {
return -1;
}
} // end of memory allocating for **R
for (i = 0 ; i < N; i++){
free(R[i]);
free(R);
}
After the program finishes, I get this error: double free or corruption (out) Aborted (core dumped)
By using valgrind for debugging, I get this message: 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
This leak is detected at this line of code (according to valgrind): *(C+i) = malloc(N * sizeof(int));
Any help on how to fix it?