Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

FormatMessage returns a char* containing nulls between each character...why?

$
0
0

When translating error messages I get back a pointer to a string (pMsgBuf) that looks like this

pMsgBuf = "T\0h\0e\0 \0s\t\0r\0a\0...."

The message is there but separated by nulls. Its got to be a parameter that I am passing to Format Message, but have no idea how to fix it.

{char* pMsgBuf;// windows will allocate memory for err string and make our pointer point to itconst DWORD nMsgLen = FormatMessage(    FORMAT_MESSAGE_ALLOCATE_BUFFER |    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,    nullptr, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),    reinterpret_cast<LPWSTR>(&pMsgBuf), 0, nullptr);// 0 string length returned indicates a failureif (nMsgLen == 0){    return "Unidentified error code";}char joe[100]{};for (int i = 0, y = 0; i < nMsgLen *2; i++){if (pMsgBuf[i] != '\0')    joe[y++] = pMsgBuf[i];}// copy error string from windows-allocated buffer to std::stringstd::string errorString = pMsgBuf;// free windows buffersize_t size = sizeof(pMsgBuf);LocalFree(pMsgBuf);return errorString;

}

Test code with watch active

Should have gotten back my string pointer back with trailing not each character with a null.

Created a test block to confirm that was what I was getting back from format message.

 char joe[100]{};    for (int i = 0, y = 0; i < nMsgLen *2; i++)    {if (pMsgBuf[i] != '\0')    joe[y++] = pMsgBuf[i];     }    

sure enough Joe the string comes out correctly.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>