Frage

I have a strange behaviour of the Messagebox started in a Thread using this code:

DWORD WINAPI CreateMessageBox(LPVOID lpParam) {
    MessageBoxA(NULL, (char*)lpParam, "", MB_OK);
    return 0;
}
std::string msg = "Hello World";
CreateThread(NULL, 0, &CreateMessageBox, msg.c_str(), 0, NULL);

While this code works normally:

DWORD WINAPI CreateMessageBox(LPVOID lpParam) {
    MessageBoxA(NULL, (char*)lpParam, "", MB_OK);
    return 0;
}
CreateThread(NULL, 0, &CreateMessageBox, "Hello World", 0, NULL);

I can't understand why it's working when it's not a variable, and if I change it to a variable, an Empty MessageBox is Displayed, but I Expected an "Hello World!.

War es hilfreich?

Lösung

msg is a local variable (allocated on stack) and it will be destroyed as soon as the function/method containing that code returns. So, the thread will be accessing invalid memory while using the lparam.

Some of the solutions could be:

1.) declare 'msg' as static - probably not a good idea
2.) allocate 'msg' on heap, but then you will have to destroy it somewhere
3.) make 'msg' a member variable
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top