I am running memcheck on my program and i’m trying to solve the memory issues.
Memcheck output :
==29633== 3,443 (128 direct, 3,315 indirect) bytes in 2 blocks are definitely lost in loss record 7 of 8
==29633== at 0x4A07D2E: operator new(unsigned long) (vg_replace_malloc.c:261)
==29633== by 0x42027F: PDcbk(cpfrCallbackType_e, Powerdomain*) (NetExtractor.cpp:1243)
==29633== by 0x413DBA: cpfparse() (cpf.y:120)
==29633== by 0x42039B: loadCPF(char*) (NetExtractor.cpp:1253)
==29633== by 0x420E5D: main (NetExtractor.cpp:1399)
==29633== LEAK SUMMARY:
==29633== definitely lost: 128 bytes in 2 blocks
==29633== indirectly lost: 3,315 bytes in 10 blocks
==29633== possibly lost: 0 bytes in 0 blocks
==29633== still reachable: 16,458 bytes in 3 blocks
==29633== suppressed: 0 bytes in 0 blocks
Line 1253 of NetExtractor is :
powerdomainMap.insert(Powerdomain_pair(powerdomain->getName(),new Powerdomain(*powerdomain)));
Info to understand the code :
PowerdomainHashMap powerdomainMap;
typedef hash_map<const string, Powerdomain*, strptrhash, strptrequal> PowerdomainHashMap;
typedef pair<const string, Powerdomain*> Powerdomain_pair;
For now my guess is that there isn’t really a leak because i still can access the newly created powerdomain from my hashmap and that valgrind isn’t able to see that.
Am I right ? If not can someone explain me ?
Thanks and feel free to ask code details as i only pasted what i thought was relevant but i might have missed something.
Well, you have map of pointers to dynamically allocated objects of class
Powerdomain.The hash map itself did not allocate that memory, so it doesn’t clean it up for you.
What you have to do is to free that memory yourself once you don’t need it, for example:
You probably never did that and Valgrind told you about that memory still being reachable upon the program termination.
Now, if you really need that data during the life time of your application, then it is OK because OS will clean that memory when program exits anyway. But of course it is much better to do a clean shutdown, so that when this problems becomes a real problem you don’t ignore it by mistreating as OK behaviour.
Aside from that, it seems like you are doing object copies anyway so I think it might be worth it to consider not working with dynamic memory explicitly and let hash_map worry about it. The data type declaration will look like this:
Hope it helps.