July 3rd, 2025
0 reactions

If the Format­Message function fails, and I requested that it allocate a buffer, do I have to free the buffer?

A customer called the Format­Message function with the FORMAT_MESSAGE_ALLOCATE_BUFFER flag, and they weren’t sure what to do if the function fails (by returning 0). Do they have to free the buffer by calling Local­Free?

No, you don’t have to free the buffer. In fact, on failure, there is no buffer. The function failed to perform the desired operation, so there is nothing to clean up.

You can make things easier on yourself by pre-initializing the output pointer to NULL. That way, if the function fails, the pointer is still null. Then your logic can be “Go ahead and free the buffer,” because the Local­Free function allows you to pass NULL, and it just ignores it. (This trick allows things like wil::unique_hlocal_string to work with FormatMessage.)

Thinking about the original question: You can’t tell whether the reason for the function failure is that something went wrong during formatting or that something went wrong during allocation of the final output buffer. You could call Get­Last­Error(), but if it returns ERROR_OUT_OF_MEMORY, you still don’t know whether it ran out of memory during the formatting phase or during the final buffer allocation phase. Therefore, even if you wanted to free the buffer, you don’t know whether you even got one in the first place.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments