Question

In this sample,the dwerror is 10045L.but this code returns 0x13d value as error. How to get the format message?Please have a look into it.

TCHAR lpMsgBuf[512];
if(!FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    dwError,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) &lpMsgBuf,
    0, NULL ))
{
    wprintf(L"Format message failed with 0x%x\n", GetLastError());
    return;
}
Was it helpful?

Solution

0x13d == 317 == ERROR_MR_MID_NOT_FOUND. The message for the error you're trying to find doesn't exist in SYSTEM. Maybe your error originate from a specific dll or driver. If you know which dll\driver try to abtain it handle and specify FORMAT_MESSAGE_FROM_HMODULE instead of FORMAT_MESSAGE_FROM_SYSTEM and supply the handle as the source in the call to FormatMessage.

And besides that if you use FORMAT_MESSAGE_ALLOCATE_BUFFER you should declare a variable of type LPTSTR like LPTSTR pMsg; and pass it to FormatMessage as (LPTSTR)&pMsg and when you're done with it use LocalFree(pMsg) to release the allocated memory.

OTHER TIPS

First of all, when you say FORMAT_MESSAGE_ALLOCATE_BUFFER, you do not need to allocate more than a pointer. Then you pass a pointer to that pointer in lpBuffer. So try this:

TCHAR* lpMsgBuf;
if(!FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    dwError,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) &lpMsgBuf,
    0, NULL ))
{
    wprintf(L"Format message failed with 0x%x\n", GetLastError());
    return;
}

And do not forget to call LocalFree

or you allocate the buffer yourself:

TCHAR lpMsgBuf[512];
if(!FormatMessage(
    FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    dwError,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) lpMsgBuf,
    512, NULL ))
{
    wprintf(L"Format message failed with 0x%x\n", GetLastError());
    return;
}

Also, try this:

#include <cstdio>
#include <cstdlib>

int alloc(char** pbuff,unsigned int n)
{
*pbuff=(char*)malloc(n*sizeof(char));
}

int main()
{
char buffer[512];

printf("Address of buffer before: %p\n",&buffer);

//  GCC sais: "cannot convert char (*)[512] to char** ... "
//  alloc(&buffer,128);

//  if i try to cast:   
alloc((char**)&buffer,128);
printf("Address of buffer after:  %p\n",&buffer);

// if i do it the right way:
char* p_buffer;
alloc(&p_buffer,128);
printf("Address of buffer after:  %p\n",p_buffer);


return 0;
}

It does not make sense to try to change the address of a variable. That is probably why your code does not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top