how to deallocate the memory allocated to the malloc in following code?
int n;
int **arr;
arr = (int**)malloc(n*sizeof(int));
for (i=0; i<n; ++i){
arr[i] = malloc(2*sizeof(int));
}
[EDIT]
*** glibc detected *** ./abc: double free or corruption (out): 0x0000000002693370
======= Backtrace: =========
/lib/libc.so.6(+0x775b6)[0x7f42719465b6]
/lib/libc.so.6(cfree+0x73)[0x7f427194ce53]
./abc[0x405f01]
/lib/libc.so.6(__libc_start_main+0xfd)[0x7f42718edc4d]
./abc[0x400ee9]
======= Memory map: ========
00400000-00416000 r-xp 00000000 08:07 392882
00616000-00617000 r--p 00016000 08:07 392882
I tried with the following mentioned answers, But i got the following above mentioned error.What can be the reason for it?
[EDIT]
The above mentioned problem is now solved. Since there was bug in the code. Now,what i am not getting is any improvement in the freed memory.What can be the reason for it?
[EDIT] I am using some modules to print the memory.following is the code
memory_Print();
#ifdef CHECK
memory_PrintLeaks();
#endif
Here memory_PrintLeaks()
prints the demanded memory and freed memory.I am getting the same value after making the changes.
One more remark what i would like开发者_高级运维 to add is, can i call the free() anywhere from the program or it is required to call from some particular locations like the place where the malloc() has been called or at the end of the program?
With free
. You must first free the memory pointed at by the arr[i]
entries, and then finally free the memory pointed at by arr
(which holds those entries). You can't do it the other way around, because freeing memory means you may no longer use the values that were in that memory.
Thus:
for (i = 0; i < n; ++i) {
free(arr[i]);
}
free(arr);
for (i=0; i<n; ++i){
free(arr[i]);
}
free(arr);
Btw, you should make sure that your allocations didn't fail, at least the one for arr
, or else you would end up dereferencing NULL pointers.
You have to loop through arr
and free arr[i]
, and then free arr when you are done. You need the same number of free calls as malloc calls.
精彩评论