Send a variable on the heap to another thread

Posted by user1201889 on Stack Overflow See other posts from Stack Overflow or by user1201889
Published on 2012-03-31T17:26:07Z Indexed on 2012/03/31 17:29 UTC
Read the original article Hit count: 194

Filed under:
|
|
|
|

I have a strange problem in C++. An address of a Boolean gets "destroyed" but it doesn't get touched. I know that there are beater way's to accomplish what I try to do, but I want to know what I do wrong.

I have a main class; this main class contains a vector of another class. There is a strange problem when a new instance gets created of this object.

This is how my code works:

There will start a thread when the constructor gets called of the “2nd”object. This thread gets as Parameter a struct. This is the struct:

struct KeyPressData
{
    vector<bool> *AutoPressStatus;
    vector<int> *AutoPressTime;
    bool * Destroy;
    bool * Ready;
};

The struct gets filled in the constructor:

MultiBoxClient::MultiBoxClient()
{
    //init data
    DestroyThread = new bool;
    ReadyThread = new bool;
    AutoThreadData = new KeyPressData;  

    //Reseting data
    *DestroyThread = false;
    *ReadyThread = false;   

    //KeyPressData configurating
    AutoThreadData->AutoPressStatus = &AutoPressStatus;
    AutoThreadData->AutoPressTime = &AutoPressTime;
    AutoThreadData->Destroy = DestroyThread;
    AutoThreadData->Ready = ReadyThread;

    //Start the keypress thread
    CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)AutoKeyThread,AutoThreadData,NULL,NULL); 
}

As long as the constructor is running will the program run fine. But when the constructor closes the address of the “AutoThreadData->Destroy” will get corrupted. The program will crash when I call the value of the pointer.

void WINAPI AutoKeyThread(void * ThreadData)
{

    KeyPressData * AutoThreadData = (KeyPressData*)ThreadData;

    while(true)
    {   
        if(*AutoThreadData->Destroy == true)    //CRASH
        {
            *AutoThreadData->Ready = true;
            return;
        }
        Sleep(100);
    }
}

What did I test:

I logged the address of the AutoThreadData and the AutoThreadData->Destroy when the constrcutor is running and clossed; the AutoThreadData address is equal to AutoThreadData when the constructor is closed. So there is no problem here.

The address of AutoThreadData->Destroy gets destroyed when the constructor is closed. But how can this happen? The Boolean is on the heap and the KeyPressData struct (AutoThreadData) is on the heap.

Destroy before: 00A85328
Destroy after: FEEEFEEE

Can someone maby explain why this crash?

I know that I can send a pointer to my class to the thread. But I want to know what goes wrong here. That way I can learn from my mistakes.

Could someone help me with this problem?

Thanks!

© Stack Overflow or respective owner

Related posts about c++

Related posts about Windows