最近写代码时,遇到一个内存泄露的问题,
Detected memory leaks!
Dumping objects ->
normal block at 0x00780E80, 16 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
在查了N久之后,才发现了这个BUG。
下面是我查找的一个过程:
1.查看所有16字节的结构体,没有发现
2.排除法,一步一步的屏蔽一些代码,才定位到这个问题
原来是在一个结构中使用了STL的string字符串类,然而在使用这个结构时,不小心memset((&sdemoinfo,0,sizeof(DemoInfo);了,导致内存泄露。如:
struct DemoInfo
{
string id;
uint8 flag ;
};
DemoInfo sdemoinfo;
memset(&sdemoinfo,0,sizeof(DemoInfo));
这样的代码是有问题,因为string类是自动管理内存,不用使用memset给包含string类型变量的结构初始化.最好的解决办法
struct DemoInfo
{
string id;
uint8 flag ;
DemoInfo() //在构造函数中初始相应的变量
{
flag = 0;
}
};