3

I've been trying to get this to work for like ages but with no avail (sad face).

int iChars = GetWindowTextLength (GetDlgItem(handle,ID))+1; // Room for '\0'
char* pstrText;
pstrText = (char*) malloc (sizeof(char)*iChars);
if (pstrText != NULL) {
    //GetWindowText (GetDlgItem(handle,ID), pstrText, iChars);
        GetDlgItemText(handle,ID,pstrText,iChars);
}
return pstrText; // Memory gets freed after it returns

Working example:

char* MWC::System::TextBox::GetText(){
    int len = SendMessage(handle, WM_GETTEXTLENGTH, 0, 0);
    char* buffer = new char[len];
    SendMessage(handle, WM_GETTEXT, (WPARAM)len+1, (LPARAM)buffer);
    return buffer;
}
Christian
  • 1,492
  • 3
  • 16
  • 19
  • Even if you reassing the pointer the memory still gets deleted so result will still point to a deleted memory. Also, the size of the pointer will be 32/64 bits depending on the plaform you are running. Fouth parameter of function GetDlgItemText has to be iChars. – beren Sep 12 '11 at 15:06
  • Yeah well , thats not what's causing the function not to work properly. – Christian Sep 12 '11 at 15:08
  • 1
    "Not working" is not good enough for us. How does it fail. Be precise. We can't see your screen. – David Heffernan Sep 12 '11 at 15:21

3 Answers3

7

The wParam parameter is wrong here:

SendMessage(handle, WM_GETTEXT, (WPARAM)len, (LPARAM)buffer);

You should pass len+1 because of the zero-terminator.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

You are freeing the memory before returning!!!

if ((pstrText != NULL) {
    GetDlgItemText(handle,ID,pstrText,sizeof(pstrText));
    free (pstrText); // Freeing memory Here!
}

You must provide a way for the client to free when its no longer needed...

Hope this helps!

beren
  • 166
  • 1
  • 8
  • Alright Thank you! Since pstrText is a local variable Its memory is supposed to be cleared after the function returns (right?). I removed free(pstrText) though now the program returns nothing. – Christian Sep 12 '11 at 15:03
  • pstrTest is a local variable. The variable gets destroyed when it comes out of scope but the memory remains allocated until you call free() on that memory. You have to figure out a way to free the memory when it is no longer needed. – beren Sep 12 '11 at 15:13
  • What about the second example? It's returning nothing as well! – Christian Sep 12 '11 at 15:18
  • Third parameter to SendMessage must be len+1. Everything else looks good, are you sure that "handle" is valid? – beren Sep 12 '11 at 15:21
2

You already free the memory pointed to by pstrText before you return. You should return a string object that can actually contain the text and frees it automatically on release. Or you'll have to ask the caller to allocate memory for the string, but then you are just wrapping the API.

demorge
  • 1,097
  • 1
  • 7
  • 17