Reputation: 3
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?
Upvotes: 0
Views: 73
Reputation: 1
This is my code to allocate memory using malloc for a 2 dimensional array in C, and to free it
An alternative approach is to make your matrix some abstract data type implemented by some (pointer to) struct
ending with a flexible array member. In such a case, your matrix creation routine makes one allocation (using malloc
), and your matrix deallacation routine can be a simple (casted) free
. Don't forget to handle failure of malloc(3) (it could happen when you want a gigantic matrix which don't fit in your computer).
Details have been given in this answer.
Read also of course Modern C and some C reference website.
IMHO two-dimensional arrays don't exist in C, you can just have arrays of arrays of some known type. Check by reading some C standard, like n2176.
Upvotes: 1
Reputation: 32594
i get this error: double free or corruption (out) Aborted (core dumped)
first notice that error is not a memory leak, the double free comes from that code
for (i=0 ; i <N ; i++){
free(R[i]);
free(R);
}
which must be must be
for (i=0 ; i <=N ; i++){
free(R[i]);
}
free(R);
else you free R in the first loop rather than after the loops
Because of that from the second loop the value of R[i]
if undefined and the behavior of the free is undefined too, and you call again free on R, both reasons compatible with the message produced by valgrind.
Note I also changed the test to be i<=N
to be the identical of the test used to do the allocations, but both suppose your array is sized N+1
(at least), else you miss a free producing a memory leak.
If the allocations step and free step are not consecutive in the code and the free step is done even you cannot allocate the memory at a given time, the code must be modified to be :
if (R != NULL)
{
for (i=0 ; i <=N ; i++){
if (R[i] == NULL) /* allocation failed */
break;
free(R[i]);
}
free(R);
}
to not dereference R if it is NULL, and to not attempts to free the entries of the array not set in the allocation loop because (*(R + i) == NULL)
was true breaking the loop
Upvotes: 2