先看一段代码:
#include <cstdlib>
#include <iostream>
using namespace std;
struct test_t {
test_t()
{
memset(this, 0, sizeof(test_t));
}
uint32_t a;
uint32_t add()
{
return a + b * c + d;
}
};
int main(int argc, char *argv[])
{
test_t t;
//memset(&t, 0, sizeof(test_t));
t.a = 4;
t.b = 1;
t.c = 2;
cout<<t.add()<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
运行结果:6
没问题;
再看代码:
#include <cstdlib>
#include <iostream>
#include <set>
using namespace std;
struct test_t {
test_t()
{
//memset(this, 0, sizeof(test_t));
}
uint32_t a;
set<int> num_set;
uint32_t add()
{
return a + num_set.size();
}
};
int main(int argc, char *argv[])
{
test_t t;
//memset(&t, 0, sizeof(test_t));
t.a = 4;
t.num_set.insert(5);
cout<<t.add()<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
运行结果:5
没问题;
然而当:
#include <cstdlib>
#include <iostream>
#include <set>
using namespace std;
struct test_t {
test_t()
{
memset(this, 0, sizeof(test_t));
}
uint32_t a;
set<int> num_set;
uint32_t add()
{
return a + num_set.size();
}
};
int main(int argc, char *argv[])
{
test_t t;
//memset(&t, 0x00, sizeof(test_t));
t.a = 4;
t.num_set.insert(5);
cout<<t.add()<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
就会出现内存出错;
原因:STL类型会自己动态的分配,如果用memset会丢失掉已分配的字符串缓冲区的内存。于是就产生了内存泄露。
所以使用memset以前,要多注意一下结构中都是什么变量。否则产生问题之后,找起来很难发现的。