3

Code looks like the following:

class A 
{
  public:
     std::string name;
};

A a;
CComBSTR textValue;
// some function which fills textValue
a.name = W2A(textValue);

Now, I've used CComBSTR so I don't have to dealloc the BString, but does W2A allocate any memory that I might have to deal with? i.e. should I have:

 char *tmp = W2A(textValue);
 a.name = tmp;
 // do something to deallocate tmp?
bpeikes
  • 3,495
  • 9
  • 42
  • 80

2 Answers2

5

Be very cautious with the W2A/A2W macros. They are implemented with "alloca" (dynamic allocation directly on the stack). In certain circumstances involving loop/recursion/long string, you will get a "stackoverflow" (no kidding).

The recommanded way is to use the "new" helpers templates. See ATL and MFC String Conversion Macros

A a;
CComBSTR textValue;
// some function which fills textValue
CW2A pszValue( textValue );
a.name = pszValue;

The conversion use a regular "in stack" buffer of 128 bytes. If it's to small, the heap is automatically used. You can adjust the trade-off by using directly the template types

A a;
CComBSTR textValue;
// some function which fills textValue
CW2AEX<32> pszValue( textValue );
a.name = pszValue;

Don't worry: you just reduced your stack usage, but if 32 bytes is not enough, the heap will be used. As I said, it's a trade-off. If you don't mind, use CW2A.

In either case, no clean up to do:-)

Beware, when pszValue goes out of scope, any pending char* to the conversion may be pointing to junk. Be sure to read the "Example 3 Incorrect use of conversion macros." and "A Warning Regarding Temporary Class Instances" in the above link.

manuell
  • 7,528
  • 5
  • 31
  • 58
  • This mention of the "new" helpers is wonderful. I've been hoping to find something that won't overrun my stack, and this is it. Thank you thank you thank you! +1! – MPW Jun 16 '17 at 14:36
  • @MPW Thanks. You'r welcome. Don't forget: code for UNICODE all the way down, and many problems will disappear... :-) – manuell Jun 16 '17 at 16:41
4

No cleanup is required because W2A allocates memory on the stack. There are certain memory-related pitfalls you have to be aware of (direct consequences of stack allocation), but nothing that looks immediately suspicious in this specific scenario.

Jon
  • 428,835
  • 81
  • 738
  • 806