现在的位置: 首页 > 综合 > 正文

谨慎使用USES_CONVERSION

2014年01月04日 ⁄ 综合 ⁄ 共 5835字 ⁄ 字号 评论关闭

谨慎使用USES_CONVERSION;,下面是从网上找到的两篇文章,大概意思就是这个宏不能使用在大的循环体和大的函数中,因为其分配的内存在函数结束的时候才能释放,所以存在堆栈溢出的问题。文章给出了解决之道以外,更深入的比较了ATL7里面的新的处理方法。

文章1原文URL: http://untidy.net/blog/2004/12/17/uses_conversion/

文章2原文URL: http://www.codeguru.com/forum/showthread.php?p=1135929#post1135929

USES_CONVERSION - a cautionary tale

December 17th, 2004

Yesterday my team at work finally got to the bottom of a crash in a product that was very difficult to track down. We had a thread running in a product that was now being required to run for much longer, and was eventually producing a stack overflow exception
(which we’d not seen before). As is the nature of such an exception, it often came from different points in the thread depending on the work that was being done.

To cut a long and painful bug-tracking story short, it turns out that the memory allocation performed by the macros related to ATL’s USES_CONVERSION text-encoding conversion system is performed by the allocafunction. This function allocates
memory on the stack (an AHA! moment) and what’s more this memory does not obey the standard stack-scoping rules:

void fn()
{
    while(true)
    {
        {
            USES_CONVERSION;
            DoSomething(A2W("SomeString"));
        }
    }
}

Some might expect the above code to release the memory allocated by A2W each time around the loop - wrong! The memory allocated by alloca does not get released until the current function is left, so to fix this problem you have to write code like this:

void fn2()
{
    USES_CONVERSION;
    DoSomething(A2W("SomeString"));
}

void fn()
{
    while(true)
    {
        fn2();
    }
}

This code was part of a Visual C++ 6 project, and apparently in VC7 there are alternative better macros that use proper stack scoping for allocation - good! We found the first signs of the true location of the bug by converting the project to VC7 and running
it there - where the stack trace exception always seemed to occur on the line where the A2W macro was being used. I think this was probably just good fortune rather than VC7 being exceptionally helpful (no pun intended!).

So: Don’t use USES_CONVERSION and friends in thread functions or tight loops - you have been warned!

=====================================================

ATL String: What's wrong with the USES_CONVERSION macros? How to avoid using them?


Q: ATL String: What's wrong with the USES_CONVERSION macros? How to avoid using them?

A: The simplest way (in ATL 3.0) to convert a Wide Character String to an ANSI String is by using OLE2A orW2A, and their equivalent MacrosSimplest,
but not the safest!

Code:

BSTR bstrMyBeaster = SysAllocString (L"Tring, Tring!");
WCHAR* pwszMyWCharString = L
"Tring, Tring!"
;

USES_CONVERSION;
LPSTR pszCharStringFromBSTR = OLE2A (bstrMyBeaster);
LPSTR pszCharStringFromLPWSTR = W2A (pwszMyWCharString);
// ...
SysFreeString (bstrMyBeaster);

Q: If it is simple and if it works, then, what's wrong in using it?

A: Macros such as OLE2AW2A and the likes cause Stack Overflows when used in loops.

The reason: 

They allocate memory using _alloca 

_alloca allocates memory on the Function Stack.
This memory is released ("popped") only on function exit. 
So, a loop that loops too often and converts strings can result in a situation where the stack has no space left to offer.

This situation causes a Stack Overflow Exception.

Sample of a Prospective Stack Overflow Exception causing Function:

Code:
int StackGuzzler (void)
{
  WCHAR* pwszTest = SOME_WCHAR_STRING;

  for (int nCounter = 0; nCounter < SOME_MAX_COUNT; nCounter++)
  {
USES_CONVERSION;
LPSTR pszCharVersion = W2A (pwszTest); // Allocated on stack
  }

  return 1;
// Stack Memory is cleared i.e. "popped" here - this is sometimes too late!

Q: How do we overcome this Stack Overflow problem?

A: By not using the macros. 

By simply delegating the string conversion to another function - one that returns the ANSI String (i.e. 'char*' or 'LPSTR' allocated on the heap/free store). 

If you are using ATL 7.0, you have the option to use a set of Conversion Classes that are better suited. Take a look at the next question for further information.

Function that safely converts a BSTR to LPSTR:

Code:
char* ConvertBSTRToLPSTR (BSTR bstrIn)
{
  LPSTR pszOut = NULL;
  if (bstrIn != NULL)
  {
int nInputStrLen = SysStringLen (bstrIn);

// Double NULL Termination
int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, bstrIn, nInputStrLen, NULL, 0, 0, 0) + 2; 
pszOut = new char [nOutputStrLen];

if (pszOut)
{
  memset (pszOut, 0x00, sizeof (char)*nOutputStrLen);
  WideCharToMultiByte (CP_ACP, 0, bstrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
}
  }
  return pszOut;
}

Function that safely converts a 'WCHAR' String to 'LPSTR':

Code:
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;
}

Using them:

Code:
LPWSTR pwszMyWideCharString = L"Tring, Tring!";
LPSTR pszSimpleCharStringFromLPWSTR = ConvertLPWSTRToLPSTR(pwszMyWideCharString);

// .. use the string


delete
 [] pszSimpleCharStringFromLPWSTR;
SysFreeString (bstrMyBeaster);
and

Code:
BSTR bstrMyBeaster = SysAllocString (L"Tring, Tring!");
LPSTR pszSimpleCharStringFromBSTR = ConvertBSTRToLPSTR(bstrMyBeaster);

// ... use the string


delete
 [] pszSimpleCharStringFromBSTR;
SysFreeString (bstrMyBeaster);
The two methods above totally erase the possibility of causing a Stack Overflow whilst converting Wide-Character Strings.

Q: Does this issue persist with ATL 7.0?

A: Fortunately, no - as you now have the option to not use these macros. Changes with ATL 7.0: 

  • ATL 7.0 claims to resolve the issue of accumulating memory allocation per loop-cycle.
  • ATL 7.0 does not require USES_CONVERSION macros.
  • ATL 7.0 provides conversion (template) classes, and not macros. 
    Code:

CW2T pszString (L"Tring Tring"); 
  
// Use it as a LPCTSTR 
std::cout << pszString;

 

For more information on how to convert strings using ATL 7.0, visit: ATL
7.0 String Conversion Classes and Macros
.

引用 3 楼 mixdd 的回复:

谢谢jennyvenus
果然微软的mvp不一样

Q: How do we overcome this Stack Overflow problem?

A: By not using the macros.

他建议不要使用 如果我就单独一个函数出来
如string getstr(CString csstr)
马上返回string可以么?



可以,但不能作为内联函数,
_alloca在所在函数结束后才修复平衡栈

string getstr(CString csstr)
{
string str;
USES_CONVERSION;
string str=T2A(url);
return str;
}

或者自行使用WideCharToMultiByte转换
#if def _UNICODE || defined UNICODE
str.reserve(url.GetLength());
WideCharToMultiByte(CP_ACP,0,url,-1,str.data(),url.GetLength(),NULL,NULL);
#elseif
str=url;
#endif

抱歉!评论已关闭.