Weird characters at the beginning of a LPTSTR? C++
I am using this code to get the windows version:
#define BUFSIZE 256
bool config::GetOS(LPTSTR OSv)
{
OSVERSIONINFOEX osve;
BOOL bOsVersionInfoEx;
ZeroMemory(&osve, sizeof(OSVERSIONINFOEX));
osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osve)) )
return false;
TCHAR buf[BUFSIZE];
StringCchPrintf(buf, BUFSIZE, TEXT("%u.%u.%u.%u"),
osve.dwPlatformId,
osve.dwMajorVersion,
osve.dwMinorVersion,
osve.dwBuildNumber);
StringCchCat(OSv, BUFSIZE, buf);
return true;
}
开发者_开发问答
And I am testing it with:
LPTSTR OSv= new TCHAR[BUFSIZE];
config c;
c.GetOS(OSv);
MessageBox(OSv, 0, 0);
And in the msgbox I get something like this äì5.1.20 (where 5.1.20 is = to OSv) but the first 2 or 3 chars are some weird characters that I don't know when they came from. Even stranger, if I call that second piece again it shows it ok, it only show the weird characters the first time I execute it.
Does someone has an idea what's going on here?
Your problem is that you should be using StringCchCopy and not StringCchCat.
StringCchCat will search until it finds a 0 in the string, and then append the result there. Since you are not initializing your output string buffer to 0's, you cannot assume it will start with a 0.
LPTSTR OSv= new TCHAR[BUFSIZE];
. <-- You've not initialized the memory block. It's filled with random garbage.
You tagged your question C++ -- is there any reason you're not using a std::vector<wchar_t>
or std::wstring
here instead of manually managing memory?
std::wstring config::GetOS()
{
OSVERSIONINFOEX osve;
BOOL bOsVersionInfoEx;
ZeroMemory(&osve, sizeof(OSVERSIONINFOEX));
osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osve)) )
return L"ERROR"; //Actually the right thing to do here is throw an exception
//but I could see how that could be a problem for some code
std::wstringstream formatter;
formatter << osve.dwPlatformId << L'.'
<< osve.dwMajorVersion << L'.'
<< osve.dwMinorVersion << L'.'
<< osve.dwBuildNumber;
return formatter.str();
}
精彩评论