慎用USES_CONVERSION
USES_CONVERSION是ATL中的一個宏定義。用于編碼轉(zhuǎn)換(用的比較多的是CString向LPCWSTR轉(zhuǎn)換)。在ATL下使用要包含頭文件#include "atlconv.h"
使用USES_CONVERSION一定要小心,它們從堆棧上分配內(nèi)存,直到調(diào)用它的函數(shù)返回,該內(nèi)存不會被釋放。如果在一個循環(huán)中,這個宏被反復(fù)調(diào)用幾萬次,將不可避免的產(chǎn)生stackoverflow。
在一個函數(shù)的循環(huán)體中使用A2W等字符轉(zhuǎn)換宏可能引起棧溢出。
#include <atlconv.h>
void fn()
{
while(true)
{
{
USES_CONVERSION;
DoSomething(A2W("SomeString"));
}
}
}
讓我們來分析以上的轉(zhuǎn)換宏
#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;
}
關(guān)鍵的地方在 alloca 內(nèi)存分配內(nèi)存上。
#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.
問題就在這里,分配的內(nèi)存是在函數(shù)的棧中分配的。而VC編譯器默認(rèn)的棧內(nèi)存空間是2M。當(dāng)在一個函數(shù)中循環(huán)調(diào)用它時就會不斷的分配棧中的內(nèi)存。
以上問題的解決辦法:
1、自己寫字符轉(zhuǎn)換函數(shù),不要偷懶
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;
}
等等一個一個的實(shí)現(xiàn)。
2、把字符轉(zhuǎn)換部分放到一個函數(shù)中處理。
void fn2()
{
USES_CONVERSION;
DoSomething(A2W("SomeString"));
}
void fn()
{
while(true)
{
fn2();
}
}
如果不知道這點(diǎn)問題,在使用后崩潰時很難查出崩潰原因的。
轉(zhuǎn)自:
http://www.cnblogs.com/carekee/articles/1935789.html