首页 > 解决方案 > 如何正确释放 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
}

标签: c++memory-managementmemory-leaks

解决方案


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.


推荐阅读