We are having a 'Entry' class like below and std map with set of Entries. at the end we clean the map but valgrind shows possible leaks of the memory allocated via strdup function.
class Entry
{
public:
char* m_key;
t m_data;
Entry(const char* key, t data)
{
m_key= strdup(key);
m_data = data;
}
~Entry()
{
free((void*)m_key);
m_key = nullptr;
delete m_data;
m_data = nullptr
}
};
Insert elements to the Map
std::map<const char*, Entry*, Predicate> map_Entries;
void Insert(const char* key, t data)
{
Entry *pNewEntry = new Entry(key, data);
map_Entries.insert(std::pair<const char*, Entry*>(pNewEntry->m_key, pNewEntry));
}
Clear element from the map
void Clear()
{
typename std::map<const char*, Entry*, Predicate>::iterator it;
for(it = map_Entries.begin(); it != map_Entries.end(); it++)
delete (*it).second;
map_Entries.clear();
}
Predicate is comparison operator like below.
struct Mapcasestr
{
bool operator()(const char* s1, const char* s2) const { return strcasecmp(s1, s2) < 0; }
};
Valgrind issue
==5666== at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==5666== by 0x8098AF9: strdup (in /usr/lib64/libc-2.17.so)
==5666== by 0x4E92B1: Entry::Entry(char const*, T*)
I am aware that using raw pointers as map keys is not a good practice and we have better options than strdup. But this is an old code base and I am trying to fix memory leaks there. What I want to know is why valgrind report possible leaks even though we free memory allocated via strdup function?