Use the ATL macro uses_conversion with caution;

Source: Internet
Author: User
Exercise caution when using uses_conversion. The following are two articles found on the Internet, which roughly means that this macro cannot be used in large loop bodies and large functions, the stack overflow problem exists because the function can be released only when it is allocated. The article gives a more in-depth comparison of the new processing methods in atl7.

Article 1 URL: http://untidy.net/blog/2004/12/17/uses_conversion/

Article 2 original URL: http://www.codeguru.com/forum/showthread.php? P = 1135929 # post1135929

Uses_conversion-a cautionary taledecember 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 was med by the macros related to ATL's uses_conversion text-encoding conversion system is already med byallocaFunction. 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 failed CT 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 convertWide character stringToANSI stringIs by using ole2a or w2a, and their equivalentMacros.Simplest, 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 ole2a, w2a and the likes causeStack overflowsWhen used inLoops.

The reason:

They allocate memory using _ alloca

_ Alloca allocates memory onFunction Stack. This memory is released ("Popped") Only on function exit.
So,Loop that loops too oftenAndConvertsStrings can result in a situation where the stack has no space left to offer.

This situation causesStack 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 onHeap/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 thatSafelyConverts 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 thatSafelyConverts 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 overflowWhilst 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 providesConversion (Template) Classes, And not macros. Code:

Cw2t pszstring (L "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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.