this post was submitted on 04 Jul 2025
1 points (100.0% liked)

Coding Blogs

424 readers
1 users here now

founded 10 months ago
MODERATORS
 

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.

The post If the Format­Message function fails, and I requested that it allocate a buffer, do I have to free the buffer? appeared first on The Old New Thing.


From The Old New Thing via this RSS feed

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here