peterphonic
peterphonic

Reputation: 1039

Why WinAPI FormatMessage fails, always returns false

I am trying to get error message from FormatMessage method, but the method always returns false and lpBuffer is null.

I would like to know whhat I am doing wrong?

Thx

LPTSTR lpBuffer = NULL;
DWORD dwError = GetLastError();
int nResult = 0;
if (dwError >= 12000 && dwError <= 12174)
{
    logger.info("dwError >= 12000 && dwError <= 12174");
    nResult = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), dwError, 0, lpBuffer, 0, NULL);
}
else
{
    logger.info("in else");
    nResult = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),lpBuffer, 0, NULL);
}

if (nResult)
{
    logger.critical("Cannot start Drools client [" + m_exe + "] because [" + lpBuffer + "]");
    //wcout << (LPWSTR)lpBuffer << endl;
    LocalFree(lpBuffer);
}
else
{
    logger.critical("Cannot start Drools client [" + m_exe + "] because [ Windows error code : " + boost::lexical_cast<string>(dwError) + " ]");
}

Upvotes: 1

Views: 1078

Answers (2)

Ben
Ben

Reputation: 35613

You are calling it wrong. If you pass FORMAT_MESSAGE_ALLOCATE_BUFFER you have to give it the location to store the buffer, so "you must cast the pointer to an LPTSTR (for example, (LPTSTR)&lpBuffer)."

I.e:

nResult = FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
    GetModuleHandle("wininet.dll"), 
    dwError, 
    0, 
    (LPTSTR)&lpBuffer, 
    BUFFER_SIZE, 
    NULL
);

See the documentation here:

Upvotes: 3

Werner Henze
Werner Henze

Reputation: 16726

You must pass &lpBuffer to FormatMessage, not lpBuffer.

Upvotes: 0

Related Questions