Brian Gradin
Brian Gradin

Reputation: 2275

C++ - How do you convert from String to TCHAR*?

Here's my code:

string str = "Hello!";
TCHAR* tch = new TCHAR[str.length() + 1];
mbstowcs_s(NULL, tch, _tcslen(tch), str.c_str(), str.length());
// Use tch for other stuff...
delete [] tch; // Gives debug heap corruption assertion

For some reason I'm getting a heap corruption assertion with this code. I'm racking my brain trying to figure what could be wrong. I can't find any good documentation for the similarities and differences between strings and tchars which would help me figure this out on my own.

Upvotes: 0

Views: 993

Answers (3)

Sergey Podobry
Sergey Podobry

Reputation: 7189

If you are asking about C++ use ATL string conversion classes for that instead of manual memory management and WinApi calls:

string str = "Hello!";
CA2T tstr(str.c_str());

SomeFunctionT(tstr);

Also you can use those classes inline:

string str = "Hello!";

SomeFunctionT(CA2T(str.c_str()));

Note: you need to include atlbase.h.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490178

You're trying to use _tcslen on tch before you initialize its contents.

From the looks of things you want something closer to:

mbstwcs_s(NULL, tch, str.length(), str.c_str(), str.length());

Upvotes: 0

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99605

_tcslen(tch) gives the wrong result since tch is not initialized at this point. I assume you should pass str.length() + 1 (the size of the buffer) there.

Upvotes: 1

Related Questions