开发者

wcstombs_s is not working properly

I am using wcstombs_s in my code to convert CString to char*. here is code:

  AddItemToListIncludeSubFolder(CString FolderPath, CString Parent)
  {
    char szInputPath[1024]; 

    memset(szInputPath,1024,'\0');
    size_t CharactersConverted=0;

    wcstombs_s(&CharactersConverted, szInputPath, FolderPath.GetLength()+1, 
        FolderPath, _TRUNCATE);
  }

It raises exception some time. Memory exception. is wcstombs_s is not working when CString is too lo开发者_如何学Gong like 1024 character or I am doing something wrong.


The third parameter of wcstombs_s is the size of the output buffer, not the size of the string to be converted. If FolderPath is longer than 1024 characters, you're writing memory out of bounds because wcstombs_s thinks it has a bigger buffer than it does.

Try this instead:

wcstombs_s(&CharactersConverted, szInputPath, sizeof(szInputPath),
    FolderPath, _TRUNCATE);


You're also using memset incorrectly, you have interchanged the second and third parameters.


should use wcstombs_s(&CharactersConverted, szInputPath, 1023, FolderPath.GetString(), _TRUNCATE); the third parameter is the buffer size of szInputPath, even FolderPath's length exceed 1024, this function still not throw exception


CString is #defined based on whther the UNICODE define is set. If it is set CString translates to CStringW otherwise to CStringA. Thing is its perfectly valid to use these classes directly. Furthermore they perform conversion between the 2.

So if you write the following code:

CStringA ansiAstring( wideString );
char* ansiCStr = ansiString.GetString();

Its as simple as that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜