我需要释放(以避免内存泄漏)以下C ++代码(std::map
,同时使用new
创建的键和值)的所有已分配内存。
int main()
{
std::map<char*, char*> *mp = new std::map<char*, char*>;
char *a = new char;
a = (char*)"abc";
char *b = new char;
b = (char*)"pqr";
mp->insert(std::pair<char*, char*>(a, b));
a = NULL , b = NULL; // no extra pointers to keys now //
printf("element : %s", (*mp)["abc"]); // working
// need to free the allocated memory by the map in here properly,
// clear() & erase() are ok? Because I think, I need some 'delete's
}
答案 0 :(得分:2)
编写同一段代码的正确和安全的方法是使用std::string
。这样,内存分配就在后台完成,您不必自己释放它。正如@PaulMcKenzie所建议的那样,使用
std::map<std::string, std::string> mp;
mp.insert({"abc", "pqr"});
但是,我了解到在生产中某些代码不是那么容易重构的,并且您可能不得不处理必须避免插入更多错误的代码。这是注释的代码,它释放了分配的内存。
int main()
{
std::map<char*, char*> *mp = new std::map<char*, char*>;
//char *a = new char; // Do not allocate memory here since 'a' will point to a
a = (char*)"abc"; // string literal and loose track of it's allocated memory
//char *b = new char
b = (char*)"pqr";
mp->insert(std::pair<char*, char*>(a, b));
a = NULL , b = NULL; // no extra pointers to keys now //
printf("element : %s", (*mp)["abc"]);
delete mp ;
// You don't need to delete the keys/values because we
// avoided allocating memory for it in the first place
}
此外,在使用char *
作为std::map
(see here)的键值时,您必须要小心,因为没有比较器时,它会比较指针而不是字符串。