Allocating/freeing memory
I am making ownerdrawn menu and when I change a menu's style to ownerdraw, I also want to store my own value in the same function(ModifyMenu). The function prototype is like this:
PHP Code:
BOOL ModifyMenu(
HMENU hMnu, // handle to menu
UINT uPosition, // menu item to modify
UINT uFlags, // options
UINT_PTR uIDNewItem, // identifier, menu, or submenu
LPCTSTR lpNewItem // menu item content
);
As, you can see that this function will allow me to pass my own value in "lpNewItem". I will be able to access this value when I recieve "WM_MEASUREITEM" or "WM_DRAWITEM" message. So I am passing the caption of the menu item. If I pass the value simply something like this:
ModifyMenu(hmenu,i, MF_BYPOSITION | MF_OWNERDRAW, 0,(char*)"My Caption");
it works but I want to get the actual caption of the menu item so I am doing this to get the capiton:
PHP Code:
char *caption;
captionlen = GetMenuString(hmenu,i, NULL, 0, MF_BYPOSITION);
caption = (char*)malloc(captionlen+1);
GetMenuString(hmenu,i, caption, captionlen+1, MF_BYPOSITION);
ModifyMenu(hmenu,i, MF_BYPOSITION | MF_OWNERDRAW, 0,(char*)caption);
free(caption)
So I first get the length of the caption, allocated memory of that length for the caption, and then passed the variable "caption" to ModifyMenu(). But right after passing the caption (it's a pointer!) to ModifyMenu(), I am free the memory allocated before. This results in messed up characters in the caption when I use it in WM_MEASUREITEM or WM_DRAWITEM. If I don't free the memory allocated for the caption, everything goes well.
So is there any performance hit if I don't free the memory? Or is there anyway I can change this code a bit so that the caption will be normal even if I free the memory?
I am doing the above stuff in a loop for each menu item and I'll never free the memory so I am just curious if this is right or not.