-2

I'm trying to get length of buffer but i get Unhandled exception error. can anyone help me please. What am I doing wrong?

case WM_COMMAND:
    switch (LOWORD(wp))
{
    case IDC_MAIN_BUTTON:
    {
        char buffer[256];

        SendMessage(hEdit,
            WM_GETTEXT,
            sizeof(buffer) / sizeof(buffer[0]),
            (LPARAM*)(buffer));
        int bl = strlen(buffer);
        MessageBox(NULL,
            bl,
            "Information",
            MB_ICONINFORMATION);
    }
        break;
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • `strlen` returns `size_t` type. Change `bl` to `size_t` type. – haccks Jan 18 '15 at 11:12
  • `SendMessage` also returns the text length. – M Oehm Jan 18 '15 at 11:14
  • 1
    My guess is that the call to `SendMessage` is failing and nothing is being written to `buffer`. Which means that it may not be null-terminated and the call to `strlen` will read beyond the end of the buffer. – David Heffernan Jan 18 '15 at 11:17

2 Answers2

2

The second parameter to MessageBox is a pointer to TCHAR. You pass an integer (and should have gotten a suitable warning at least).

You must first convert the integer to a string representation, for example in non-Unicode build:

    int bl = strlen(buffer);
    char buf[20];

    _snprintf(buf, sizeof(buf), "%d", bl);

    MessageBox(NULL, buf, "Information", MB_ICONINFORMATION);

(Caveat: Code not tested.)

M Oehm
  • 28,726
  • 3
  • 31
  • 42
0

Besides the mistake mentioned by M Oehm there are two more issues here:

  1. The outcome of SendMessage() is not tested.
  2. The buffer passed is uninitialised and is passed to strlen() in any case, so if not being set to a C-"string", that is contains as least one '\0' to serve as a 0-terminator, the call to strlen() will fail.

To fix this at least change this:

char buffer[256];

to become

char buffer[256] = "";
Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255