c++pointersscopeformatmessage

Write a function that will return string after fetching message using FormatMessage


I wanted to write a function that will take error_code as argument and fetch the error message and the return the message. But for FormatMessage the memory allocated is cleared by using LocalFree(err_msg). Not sure how can this be dont along with returning.

static char* return_message(int error_code) {
   LPTSTR err_msg;
   FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
            0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&err_msg, 0, 0);
  return err_msg;

I want to have a method similar to above. While in above case if we return err_msg it goes out of scope. Can anyone please give the proper function for this?


Solution

  • Seeing as you're using C++ you can copy the resulting message into an std::string instance, free the C-string and return the copy. std::string's destructor will take care of deallocation when its no longer used.

    #include <string>
    #include <windows.h>
    
    static std::string return_message(int error_code) {
       char* tmp_msg;
       FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
                0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPSTR)&tmp_msg, 0, 0);
    
       std::string err_msg(tmp_msg);
       LocalFree(tmp_msg);
       return err_msg;
    }