Recently, I was spending time on making data structure library memory leak free using valgrind.
So, posting what I learned from using valgrind. Though things are very simple, it helps in writing better code.
The data structure library can be found here : https://github.com/cpaithane/cp_ds_lib/tree/master/src
===============
Valgrind error symptom : invalid write of 1 byte.
1. strlen returns output excluding '/0' character. So, if malloc or character array
is used to allocating memory, allocate strlen(str) + 1 number of bytes.
2. Also, string should terminate with '/0' character. Something like as follow :
str[strlen(str)] = '\0';
===============
Valgrind error symptom : invalid read of 4 bytes.
1. This error was coming out of removal of singly linked list. The list was
traversed as follow :
tmp = head;
while (tmp)
{
i++;
head = sll_remove_node_0(head);
tmp = tmp->sll_next;
}
2. As part tmp = tmp->sll_next; code is accessing recently freed memory. The memory
is freed by sll_remove_node_0().
3. Fixed as follow :
while (head)
{
i++;
head = sll_remove_node_0(head);
}
4. Lesson learned : Always look at pointer after freeing of memory.
==============
Valgrind error symptom : Source and destination overlap in
memcpy(0x4207278, 0x4207278, 4)
How to fix :
node = malloc(len);
memcpy(node, temp, len);
Proceed further.
==============
Valgrind error symptom : Conditional jump or move depends on uninitialised value(s)
head of linked list was uninitialized and it was checked for some decision making.
Initialize the pointer to NULL.
==============