关于cstring ->string-> const char * 用U2A一步转换 错误的内存问题

 1 // CStringTest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <string>
 7 #include <atlstr.h>
 8 
 9 using namespace std;
10 
11 static std::string U2A(CString cstring)
12  {
13     if (::IsBadStringPtr(cstring,-1))
14         return "";
15 
16     int cchStr = ::WideCharToMultiByte(CP_ACP, 0, cstring, -1, NULL, 0, NULL, NULL);
17     char* pstr = new char[cchStr + 1];
18     if(pstr != NULL)
19         ::WideCharToMultiByte(CP_ACP, 0, cstring, -1, pstr, cchStr, NULL, NULL);
20 
21     pstr[cchStr] = '';
22     std::string str(pstr);
23     delete []pstr;
24     return str;
25 }
26 
27 static CString A2U(const std::string& sstring)
28 {
29     int cchStr = (int) sstring.length() + 1;
30     wchar_t* pwstr = new wchar_t[cchStr];
31     if(pwstr != NULL)
32         ::MultiByteToWideChar(CP_ACP, 0, sstring.c_str(), -1, pwstr, cchStr);
33 
34     CString strTmp(pwstr);
35     delete []pwstr;
36     return strTmp;
37 }
38 
39 int _tmain(int argc, _TCHAR* argv[])
40 {
41     CString cstr = _T("this is cstring");
42     //正确
43     string str = U2A(cstr);
44     const char *p = str.c_str();  
45     //正确
46     std::string p1 = (U2A(cstr)).c_str();
47     //错误 //错误可能原因:U2A函数返回的是string类型局部变量,
48     //出了函数范围,局部变量指针被释放,但是开辟的内存区域还没有释放,
49     //由于没有像上面那样用string类型对象重新开辟内存用于接收返回的局部变量的内容。
50     //const char* p2 指向了已经释放了的指针
51     const char* p2 = U2A(cstr).c_str();  //错误
52     cout << p << endl;
53     cout << p1 << endl;
54     cout << p2 << endl;
55     system("pause");
56     return 0;
57 }
View Code
原文地址:https://www.cnblogs.com/lisuyun/p/3622762.html