Skip to content
This repository has been archived by the owner on Feb 12, 2025. It is now read-only.

GetLastErrorAsString leaks memory #52

Open
sredna opened this issue Jun 4, 2023 · 0 comments
Open

GetLastErrorAsString leaks memory #52

sredna opened this issue Jun 4, 2023 · 0 comments

Comments

@sredna
Copy link

sredna commented Jun 4, 2023

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

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...

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant