在插入C STL地图之前,我需要使用新的内存分配内存

Do I need to to allocate memory using new before insert into a C++ STL map?

本文关键字:内存 分配 STL 插入 地图      更新时间:2023-10-16

i具有以下功能,该功能将对插入stl映射。在插入之前,我需要使用新的内存分配内存?

char* foo(char* lnumber)
{
       char* sData = “A,B,C”;
       Char delim[] = “,”;                       
       typedef std::map<std::string, std::string> TStrStrMap; 
       typedef std::pair<std::string, std::string> TStrStrPair;
       TStrStrMap tMap;
       if(strstr(sData,delim) != 0)
       {
          tok = strtok( sData, delim);
          while( ( tok != NULL))
          {
             int bytes = strlen(tok)+1;
             char* ll = new char[bytes];
             memset(ll,0,bytes);
             strcpy(ll,tok);
             ll[bytes] = '';
             int bytes1 = strlen("yes")+1;
             char* ll1 = new char[bytes1];
             memset(ll1,0,bytes1);
             strcpy(ll1,”yes”);
             ll1[bytes1] = '';
             tMap.insert(TStrStrPair(ll,ll1));
             tok = strtok( NULL, delim);
          }
        }
        std::string strValue = tMap[lnumber];
        return(strdup(strValue.c_str()));
}

回答您的特定问题 - 不,考虑到您所显示的声明,您不需要自己分配内存。std::string将管理字符串值的内存,std::pair将处理其std::string值的内存,std::map将处理其std::pair值的内存。

您的当前代码正在泄漏您分配给" new []'的每个char[]缓冲区。您的std::string值正在制作数据副本,因此您需要在使用它们时delete[],例如:

char* foo(char* lnumber)
{
    char sData[] = "A,B,C";
    char *delim = ",";                       
    typedef std::map<std::string, std::string> TStrStrMap; 
    typedef std::pair<std::string, std::string> TStrStrPair;
    TStrStrMap tMap;
    if(strstr(sData, delim) != 0)
    {
        char *tok = strtok(sData, delim);
        while (tok != NULL)
        {
            int bytes = strlen(tok)+1;
            char* ll = new char[bytes];
            strcpy(ll, tok);
            int bytes1 = strlen("yes")+1;
            char* ll1 = new char[bytes1];
            strcpy(ll1, "yes");
            tMap.insert(TStrStrPair(ll,ll1));
            delete[] ll; // <-- here
            delete[] ll1; // <-- here
            tok = strtok( NULL, delim);
        }
    }
    std::string strValue = tMap[lnumber];
    return strdup(strValue.c_str());
}

话虽如此,由于std::string具有接受char*输入的构造函数,因此您的循环代码可以大大简化为以下内容:

// you really should be using std::string instead
// of char* for the function's input and output...
//
char* foo(char* lnumber)
{
    char sData[] = "A,B,C";
    char *delim = ",";                       
    typedef std::map<std::string, std::string> TStrStrMap; 
    typedef std::pair<std::string, std::string> TStrStrPair;
    TStrStrMap tMap;
    char *tok = strtok(sData, delim);
    while (tok != NULL)
    {
        tMap.insert(TStrStrPair(tok, "yes"));
        tok = strtok(NULL, delim);
    }
    std::string strValue = tMap[lnumber];
    return strdup(strValue.c_str());
}