pointers - How to avoid memory leaks, with C++ with STL containers? -
pointers - How to avoid memory leaks, with C++ with STL containers? -
code snippet below:
//container declared map<string, structa*>& amap; // allocation , insertion container structa *item = new structa(); amap["arrdevaddr"] = item; however iterate , free map value (pointer) @ end of map getting used.
now, due above code snippet, valgrind flagging me "definitely leaked" message.
i want clarify, general principle of coding avoid memory leak. per understanding, in (c++ coding):
when allocate memory, entitled free aswell, limted overall span of code. when maintain allocated memory in container (e.g. map here), still need retain pointers (allocations), until map using pointers. which means, allocate >> add together pointer container >> usage of pointers in map >> ensure "deleting/freeing" struct-pointers, when map utilize over, or if map contained in object, in object's "destructor", map should iterated , struct-pointers should freed.correct me, if wrong in understanding.
second case:
class a{ ... map<string, structa*>& amap; ... } now in other class, map inserted value as;
if(..) { structa item; aobj->amap["arrdevaddr"] = &item; } ... now, in case, "item" local scope, map containing "dangling references"? if not, how? in such scenario's should way ensure, avoid memory-leaks while coding?
don't delete or free things yourself. utilize memory-managing class- these immune memory leaks , such related problems unless work hard stupid.
in case unique_ptr fine, or storing structa value.
c++ pointers memory-leaks
Comments
Post a Comment