"String is not null terminated" error

I have the following code:

GetMyName() returns a std::wstring value.

1
2
3
4
5
6
7
8
9
wchar_t szCmd_begin[] = {L't',L'e',L's',L't',L'\0'};
        int buflen = (GetMyName().size()*sizeof(wchar_t)) + sizeof(szCmd_begin) + sizeof(szCmd_end);
wchar_t szCmd_end[] = {L't',L'e',L's',L't',L'\0'};

        wchar_t *szCmd = new wchar_t[buflen];
	
	wcscpy_s(szCmd, sizeof(szCmd_begin), szCmd_begin);
	wcscat_s(szCmd, (GetMyName().size()*sizeof(wchar_t)),GetMyName().c_str());
	wcscat_s(szCmd, sizeof(szCmd_end), szCmd_end);


If I comment out the last line, the code works just fine; concatenates the szCmd_begin and the GetMyName wstring and I can print it out just fine.

After the the third wchar function, however, the program fails and tells me that the string is not null terminated.

This is strange, because I've included the null character in both the szCmd_begin and szCmd_end, and the wstring function c_str() always adds the null character.

Also, the wchar array copy and concatenate function takes into account the position of null characters when modifying strings.

Before anyone says "why are you using a wchar array when you can just use wstring, so much easier?!" Yes I know, however, I'm passing it through a function that requires a non-const wchar array, so c_str() itself will cause an error.

Any help is appreciated, thanks.
You really don't need to write such obtuse looking string declarations.
1
2
wchar_t szCmd_begin[] = L"test";
wchar_t szCmd_end[] = L"test";


The buffer passed in to the _s functions is always the size of the buffer.
1
2
3
4
5
wchar_t *szCmd = new wchar_t[buflen];
	
wcscpy_s(szCmd, buflen, szCmd_begin);
wcscat_s(szCmd, buflen, GetMyName().c_str());
wcscat_s(szCmd, buflen, szCmd_end);

Topic archived. No new replies allowed.