c++ - 如何正确释放 std::map 的内存
问题描述
我需要释放(以避免内存泄漏)为以下 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
}
解决方案
The correct and safe way to write the same piece of code is to use std::string
. This way, memory allocation is done behind the scene and you don't have to free it yourself. As proposed by @PaulMcKenzie, use
std::map<std::string, std::string> mp;
mp.insert({"abc", "pqr"});
However, I understand that in production some piece of code are not that easy to refactor and that you may have to work with what you have to avoid inserting more bugs. Here is the commented code that frees the allocated memory.
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
}
Moreover, you need to be careful when working with char *
as key value of std::map
(see here) since without comparator, it compares the pointers, not the strings.
推荐阅读
- apache-spark - 使用 spark 读取雪花表时遇到 classnotfound 异常
- nginx - Nginx rewrite 和 proxy_pass 解释
- c++ - C ++使用std库找到满足条件的向量中的第一个元素
- reactjs - 使用 fireEvent 发送值
- typescript - Typescript - 导入第三方模块 - 名称自动完成 VSCode
- c# - WPF - 棱镜区域和祖先绑定的相对源问题
- oracle - 使用 logstash 将 300 万条记录从 Oracle 迁移到 Elastic Search
- google-cloud-storage - 重试策略未转发到谷歌客户端
- python - NER 德国自然物体
- html - 固定标题隐藏在导航栏后面