I seem to be misunderstanding the GetWindowText function. I though you are supposed to pass a buffer where the function can write the title, so that means that the buffer has to be (in UNICODE):
(size of the title) * 2 + 2
multiply by 2 because each UNICODE character is 2 bytes wide, and + 2 for the zero terminating sign.
Am I right so far?
But how in the world does this work?
Also after im done using the pointer to the title do I just call GlobalFree() to free the space?
LPWSTR lp = (LPWSTR)GlobalAlloc(GPTR, 1);
GetWindowText(hwnd, lp, GetWindowTextLength(hwnd)+1);
MessageBox(NULL, lp, lp, 0);
It works because of memory allignment. A bigger chunk of memory can be allocated then what you requested. It would be very bad to depend on this though.
I don't think i quite understand what you said.
Just because you request 1 byte to be allocated doesn't mean only one byte will be - you might get a bigger chunk, still "guaranteed to be aligned on an 8-byte boundary" (see GlobalAlloc) but, as Quantum1024 has already pointed out, you shouldn't rely on this. You can always try using the GlobalSize function to determine the size of memory returned.
Thanks guys, I finaly understand this.
So when the function asks for a pointer to a buffer the pointer is really pointing to the begining of the buffer, and the function assumes that there is enough space allocated, but if there isn't it just keeps writting into the memory following the one you have already alocated.
I though windows had some kind of mechanism to check for this kind of stuff, but I guess not.