在插入C STL地图之前,我需要使用新的内存分配内存
Do I need to to allocate memory using new before insert into a C++ STL map?
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());
}
相关文章:
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配