Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in string WindowsTcpSocketClient::GetErrorMessage(const int &e) #266

Open
VersusQ opened this issue Apr 4, 2019 · 0 comments
Open

Comments

@VersusQ
Copy link

VersusQ commented Apr 4, 2019

We face to problem with your library.

We builded it with Visual Studio compiler and with definition UNICODE.
The library was builded successfully.

But late we noticed invalid error messages in our log.
Their cause is function WindowsTcpSocketClient::GetErrorMessage().
The function call FormatMessage() and return its result as std::string.
But in our situation FormatMessage() returns utf-16 string and your code casts it to char*.

I suggest you 2 correct cases.
First case returns ANSI string.
Second case returns UTF8 string.
Choose more appropriate case.

// ANSI
std::string WindowsTcpSocketClient::GetErrorMessage(const int &e)
{
	std::string message = "Unknown error";

	const char* lpMsgBuf;
	DWORD dwResult = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(char*)&lpMsgBuf, 0, NULL);

	// if not error
	if (dwResult != 0)
	{
		message = lpMsgBuf;
		LocalFree((HLOCAL)lpMsgBuf);
	}

	return message;
}
// UTF-8
std::string WindowsTcpSocketClient::GetErrorMessage(const int &e)
{
	std::string message = "Unknown error";

	const WCHAR* lpMsgBuf;
	DWORD dwResult = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(WCHAR*)&lpMsgBuf, 0, NULL);

	// if not error
	if (dwResult != 0)
	{
		// convert to utf8
		std::wstring wstr = lpMsgBuf;
		LocalFree((HLOCAL)lpMsgBuf);

		if (!wstr.empty())
		{
			int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
			std::string u8str(size_needed, 0);
			WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &u8str[0], size_needed, NULL, NULL);
			message = u8str;
		}
	}

	return message;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant