code snippet below:
//container declared
map<string, structA*>& aMap;
// allocation and insertion to container
structA *item = new structA();
aMap["arrDevAddr"] = item;
However I iterate and free the map value (pointer) at the end of the map getting used.
Now, due to above code snippet, valgrind is flagging me as "definitely leaked" message.
I want to clarify, the general principle of coding to avoid memory leak. As per my understanding, in (C++ coding):
correct me, if I am wrong in my understanding.
SECOND CASE:
class A{
...
map<string, structA*>& aMap;
...
}
now in some other class, the map is inserted with value as;
if(..)
{ structA item;
aObj->aMap["arrDevAddr"] = &item;
}
...
Now, in this case, as "item" is local to the scope, will the map be containing the "dangling references"? If not, how? In such scenario's what should be the way to ensure, we avoid any memory-leaks while coding?
Don't delete
or free
things yourself. Always use a memory-managing class- these are completely immune to memory leaks and such related problems unless you work very hard to do something very stupid.
In this case something like unique_ptr
would be fine, or even just storing structA
by value.
You would avoid memory leaks by storing a std::unique_ptr rather than a raw pointer:
#include <iostream>
#include <map>
#include <memory>
#include <string>
struct structA {};
using structA_ptr = std::unique_ptr<structA>;
//container declared
std::map<std::string, structA_ptr> aMap;
using namespace std;
int main()
{
aMap.emplace("bob", structA_ptr { new structA {} });
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.