1
#ifdef UNICODE
2 #ifndef TSTRING
3 #define TSTRING std::wstring
4 #endif
5 #else
6 #ifndef TSTRING
7 #define TSTRING std::string
8 #endif
9 #endif
10
11 #define MAX_OBJ_NUM 10
12
13 struct Object
14 {
15 UINT id;
16 TSTRING strIconPath;
17 TSTRING strAppPath;
18 };
19
20 Object obj[MAX_OBJ_NUM ];
21
22 void InitObject(Object& obj )
23 {
24 memset( & Obj[ 0 ], 0 , sizeof (Object) * MAX_OBJ_NUM );
25 }
2 #ifndef TSTRING
3 #define TSTRING std::wstring
4 #endif
5 #else
6 #ifndef TSTRING
7 #define TSTRING std::string
8 #endif
9 #endif
10
11 #define MAX_OBJ_NUM 10
12
13 struct Object
14 {
15 UINT id;
16 TSTRING strIconPath;
17 TSTRING strAppPath;
18 };
19
20 Object obj[MAX_OBJ_NUM ];
21
22 void InitObject(Object& obj )
23 {
24 memset( & Obj[ 0 ], 0 , sizeof (Object) * MAX_OBJ_NUM );
25 }
调用InitObject()的时候会有内存泄露发生,很是郁闷,我只是0初始化了呀。
经查证,发现是对字符串清零时出的问题。
原因如下:string/wstring是C++标准库的类,而用memset来对包含有指针的类对象的结构体清0是非常危险的,该清0操作导致string/wstring的内部结构遭到破坏,已经申请到的内存得不到释放,因而导致内存泄露。
解决办法:
1
//
笨方法,逐一清0
2 void InitObject(Object & obj)
3 {
4 for ( int i = 0 ; i < MAX_OBJ_NUM; i ++ )
5 {
6 obj[i].id = 0 ;
7 obj[i].strIconPath.clear();
8 obj[i].strAppPath.clear();
9 }
10 }
2 void InitObject(Object & obj)
3 {
4 for ( int i = 0 ; i < MAX_OBJ_NUM; i ++ )
5 {
6 obj[i].id = 0 ;
7 obj[i].strIconPath.clear();
8 obj[i].strAppPath.clear();
9 }
10 }