慎用USES_CONVERSION
USES_CONVERSION是ATL中的一個宏定義。用于編碼轉換(用的比較多的是CString向LPCWSTR轉換)。在ATL下使用要包含頭文件#include "atlconv.h"
使用USES_CONVERSION一定要小心,它們從堆棧上分配內存,直到調用它的函數返回,該內存不會被釋放。如果在一個循環中,這個宏被反復調用幾萬次,將不可避免的產生stackoverflow。
在一個函數的循環體中使用A2W等字符轉換宏可能引起棧溢出。
#include <atlconv.h>
void fn()
{
while(true)
{
{
USES_CONVERSION;
DoSomething(A2W("SomeString"));
}
}
}
讓我們來分析以上的轉換宏
#define A2W(lpa) (\
((_lpa = lpa) == NULL) ? NULL : (\
_convert = (lstrlenA(_lpa)+1),\
ATLA2WHELPER((LPWSTR) alloca(_convert*2), _lpa, _convert)))
#define ATLA2WHELPER AtlA2WHelper
inline LPWSTR WINAPI AtlA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars, UINT acp)
{
ATLASSERT(lpa != NULL);
ATLASSERT(lpw != NULL);
// verify that no illegal character present
// since lpw was allocated based on the size of lpa
// don't worry about the number of chars
lpw[0] = '\0';
MultiByteToWideChar(acp, 0, lpa, -1, lpw, nChars);
return lpw;
}
關鍵的地方在 alloca 內存分配內存上。
#define alloca _alloca
_alloca
Allocates memory on the stack.
Remarks
_alloca allocates size bytes from the program stack. The allocated space is automatically freed when the calling function
exits. Therefore, do not pass the pointer value returned by _alloca as an argument to free.
問題就在這里,分配的內存是在函數的棧中分配的。而VC編譯器默認的棧內存空間是2M。當在一個函數中循環調用它時就會不斷的分配棧中的內存。
以上問題的解決辦法:
1、自己寫字符轉換函數,不要偷懶
Function that safely converts a 'WCHAR' String to 'LPSTR':
char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)
{
LPSTR pszOut = NULL;
if (lpwszStrIn != NULL)
{
int nInputStrLen = wcslen (lpwszStrIn);
// Double NULL Termination
int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
pszOut = new char [nOutputStrLen];
if (pszOut)
{
memset (pszOut, 0x00, nOutputStrLen);
WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
}
}
return pszOut;
}
等等一個一個的實現。
2、把字符轉換部分放到一個函數中處理。
void fn2()
{
USES_CONVERSION;
DoSomething(A2W("SomeString"));
}
void fn()
{
while(true)
{
fn2();
}
}
如果不知道這點問題,在使用后崩潰時很難查出崩潰原因的。
轉自:
http://www.cnblogs.com/carekee/articles/1935789.html