When using the `FORMAT_MESSAGE_ALLOCATE_BUFFER` flag you are supposed to `LocalFree` the returned string at some point. If you are single-threaded you can do something like ```C LPSTR GetLastErrorAsString() { UINT err = GetLastError(); static LPSTR str = NULL; if (str) LocalFree(str), str = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|..., err, ..., (LPSTR) &str, ...); return str; } ``` This will leak one string in total instead of one for each call. If you are multi-threaded you might want to use TLS or add the strings to a list you free later...
When using the
FORMAT_MESSAGE_ALLOCATE_BUFFERflag you are supposed toLocalFreethe returned string at some point.If you are single-threaded you can do something like
This will leak one string in total instead of one for each call.
If you are multi-threaded you might want to use TLS or add the strings to a list you free later...