Arks
Arks

Reputation: 639

WinApi FormatMessage causes segfault

I use CodeBlocks and Mingw: g++ version is 4.7.1

The example from MSDN (see the last example, just before 'Requirements' section):

// Formats a message string using the specified message and variable
// list of arguments.
LPWSTR GetFormattedMessage(LPWSTR pMessage, ...)
{
   LPWSTR pBuffer = NULL;

   va_list args = NULL;
   va_start(args, pMessage);

   FormatMessage(FORMAT_MESSAGE_FROM_STRING |
              FORMAT_MESSAGE_ALLOCATE_BUFFER,
              pMessage, 
              0,
              0,
              (LPWSTR)&pBuffer, 
              0, 
              &args);

   va_end(args);

   return pBuffer;
}

It segfaults on call to FormatMessage. Do you have any idea why is this happening and how I can fix this?

This is how I call it:

int x = 3, y = 5;
GetFormattedMessage(_T("%1 : %2"), x, y);

I used FormatMessage because I cannot use _stprintf function on mingw,_stprintf is a define to swprintf and swprintf itselft is not defined there as a fix to some of there bugs %)

Upvotes: 0

Views: 296

Answers (1)

The Dark
The Dark

Reputation: 8514

FormatMessage requires that you pass the type information in the message string. If you don't it assumes that your parameters are C style strings. MSDN says:

The default is to treat each value as a pointer to a null-terminated string.

As you are passing integers, rather than strings, your call should be something like:

GetFormattedMessage(_T("%1!d! : %2!d!"), x, y);

Upvotes: 3

Related Questions