简体   繁体   中英

How to avoid memory leaks, with C++ with STL containers?

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):

  1. when we allocate a memory, we are entitled to free it aswell, limted by the overall span of code.
  2. when we keep the allocated memory in some container (eg map here), we still need to retain those pointers (allocations), until the map is using those pointers.
  3. which means, allocate >> add pointer to container >> usage of pointers in the map >> ensure "deleting/freeing" the struct-pointers, when the map use is over, or if the map is contained in some object, then in the object's "destructor", map should be iterated and struct-pointers should be freed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM