Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to format the output of Win32's GetLastError() method into a string using FormatString
DWORD dLastError = GetLastError();
LPCTSTR strErrorMessage = NULL;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dLastError,
0,
(LPWSTR) &strErrorMessage,
0,
NULL);
//Prints debug output to the console
OutputDebugString(strErrorMessage);
@nazikus
Copy link

nazikus commented May 29, 2014

for consistency, change casting from LPWSTR to LPTSTR at line 9

@aianau
Copy link

aianau commented Jun 7, 2019

You will have a memory leak

@Aaronontheweb
Copy link
Author

Aaronontheweb commented Jun 2, 2020

@aianau at which part?

@kroppt
Copy link

kroppt commented Dec 29, 2020

https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessage

FORMAT_MESSAGE_ALLOCATE_BUFFER
The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the address specified by lpBuffer.
[...]
The caller should use the LocalFree function to free the buffer when it is no longer needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment