'Why does GetKeyState work properly when it is on the stack, but when it is on the heap it causes a silent exit?

I might be missing something obvious, and forgive me if I am.

Anyways, I have a class Keys which has method SPrintScreen as follows:

class Keys{
    uint32_t sentQM;

    // create array to be passed to SendInput function
    INPUT printscreen[2];

    // set both types to keyboard events
    printscreen[0].type = INPUT_KEYBOARD;
    printscreen[1].type = INPUT_KEYBOARD;

    // assign printscreen key
    printscreen[0].ki.wVk = VK_SNAPSHOT;
    printscreen[1].ki.wVk = VK_SNAPSHOT;

    // add key up flag to second input
    printscreen[1].ki.dwFlags = KEYEVENTF_KEYUP;

    void SPrintScreen(){
        sentQM = SendInput(2, printscreen, sizeof(INPUT));
        if (sentQM != ARRAYSIZE(printscreen)){
            std::cout << "could not simulate print screen" << std::endl;
        }
    }
}

When I create the Keys object on the stack (Keys keys;) then call SPrintScreen ( keys.SPrintScreen() ), things work as expected, and the pressing of the print screen key is simulated and the program can continue running.

However when I create the Keys object on the heap (Keys* keys;), and call SPrintScreen ( keys->SPrintScreen() )the program just silently exits without any indication of why, not even a message in the console.

How is this working only sometimes?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source