iegrm
iegrm

Reputation: 79

Printing GetWindowTextA is wrong when printing outside function

I'm quite new to C++, coming from C# background, so forgive me if this is a dumb question.

I have the following function for getting the title of a window by handle.

char* GetWindowTitle(HWND hwnd) {
    char winTitle[56];
    GetWindowTextA(hwnd, winTitle, sizeof(winTitle));
    printf("Title: %s\n", winTitle);

    return winTitle;
}

The printf in this function correctly outputs Title: a.txt - Notepad.

But if I do the same with the return from the function:

printf("Title: %s\n", GetWindowTitle(hwnd));

The output is now "Title: `÷S"

What's causing this different behaviour?

Upvotes: 0

Views: 62

Answers (1)

pm100
pm100

Reputation: 50180

You are returning the address of something that is local to the function. It only exists for the duration of that function.

char* GetWindowTitle(HWND hwnd) {
    char winTitle[56];  <====== this is destroyed when the function ends
    GetWindowTextA(hwnd, winTitle, sizeof(winTitle));
    printf("Title: %s\n", winTitle);

    return winTitle;
}

Try this instead:

#include <string>

std::string GetWindowTitle(HWND hwnd) {
    char winTitle[56];
    GetWindowTextA(hwnd, winTitle, sizeof(winTitle));
    printf("Title: %s\n", winTitle);

    return std::string(winTitle);
}

This will allocate a std::string on the heap. Once you no longer reference it in the calling code, it will be deleted.

To display this string with printf(), do:

printf("Title: %s\n", GetWindowTitle(hwnd).c_str());

Though, you should get out of the habit of using C-style I/O (printf(), etc). To display this string with C++-style I/O, do:

#include <iostream>

std::cout << "Title: " << GetWindowTitle(hwnd) << std::endl;

If you intend to write a lot of C ++ code, learn to use:

  • std::string (string in C#)
  • std::shared_ptr and std::unique_ptr (class object reference in C#)
  • std::vector (List in C#)
  • std::map (Dictionary in C#)

Upvotes: 1

Related Questions