慎用USES_CONVERSION(轉自ALCAT專欄)

首先,先介紹下USES_CONVERSION爲何物。

USES_CONVERSION是ATL中的一個宏定義。用於編碼轉換(用的比較多的是CString向LPCWSTR轉換)。通俗的說,就是你用了這個宏後,就可以用一系列的字符串轉換宏,有OLE到T,T到OLE,OLE到W,W到OLE等等,非常方便。或者說,這個宏會告訴編譯器,在緊接的代碼中我們要用ole庫中代碼(如ansi   到unicode   的A2W(...))的轉換宏,不加USES_CONVERSION在使用A2W會出錯。

要想使用這個宏,因爲它是ATL庫帶的,所以要加上頭文件 #include <atlconv.h>。


關於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();
    }
}

如果不知道這點問題,在使用後崩潰時很難查出崩潰原因的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章