I found myself wanting to retrieve the text of a menu item with the GetMenuItemInfo function. The first thing that I noticed was that getting the text required the classic Win32 dance of "call the function, see how long the text is, allocate a buffer, call the function again." (I'll have you know that such dances are exceptionally painful with PInvoke, but at least I was writing in normal C++.) Basically, this function's first call produces the length of the buffer via the ccb member of the menu item information structure.
The surprise came when I found that the heap was corrupted after the second call of GetMenuItemInfo! It turns out that the length is reported in characters, not bytes, which is super misleading and not noted anywhere, as far as I can tell. (All the examples on the Internet always allocated a buffer of 256 bytes, which is a bit wasteful.) So, rather than allocating a buffer of ccb + 1, you need a buffer of (ccb + 1) * 2 thanks to the wideness of the characters in LPWSTRs.
No comments:
Post a Comment