I have a complex C code with me and while executing it, I chanced upon the following errors:
- glibc: corrupted double-linked list
- glibc: malloc() memory corruption
- munmap_chunk() invalid pointer
I realized 1) is associated with freeing already freed memory. I am still trying to figure out the reasons for 2) and 3).
Well, the thing is then I did some searches and got the general opinion that I must debug with "valgrind" to detect memory corruption related problems.
Ok, coming back to the point,when I searched this forum, I have just dug up some code posted at: What is the best way to free memory after returning from an error?
And this piece of code had solved my problems:
int func(void **mem1, void **mem2)
{
*mem1 = NULL;
*mem2 = NULL;
*mem1 = malloc(SIZE);
if(!*mem1)
goto err;
*mem2 = malloc(SIZE);
if(!*mem2)
goto err;
return 0;
err:
if(*mem1)
free(*mem1);
if(*mem2)
free(*mem2);
*mem1 = *mem2 = NULL;
return 1;
}
Well what really solved my issue is the line:
eg:
char *ptr = NULL;
ptr = (char *)malloc(SIZE);
assign and use ptr
free(ptr);
How is char *ptr = NULL helping???? Infact when I assigned to NULL in the beginning, I didn't even use free(ptr). It still worked liked a charm(I tried executing several times)
When I remove the NULL assignment in the beginning I get error 1) :( :(
I am going to install Valgrind but before that I would like some insights on this.
Thanks