Question


I'm trying to pass a structure to my thread using CreateThread() and here is my structure :

struct Secure
{
  int UID;
  LPVOID MainClass;
};

And here is the way I call CreateThread()

Secure m_Secure = {Room->g_User[PlayerNumber].UID,this};

CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,&m_Secure,NULL,NULL);

Which the first one is integer and the second one is a pointer to the current class.
And, here is my thread and I think that here is the problem

HRESULT WINAPI SecureThread(LPVOID Param)
{
    int UID = -1, UserNumber, i;

    Secure* m_Secure = (Secure*)Param;

    UID = m_Secure->UID;

    CGGCBotDlg *h_MainClass = (CGGCBotDlg*)m_Secure->MainClass;

    if (UID == -1) return 0;

    Sleep(25000);

    for (i = 0; i < TOTAL_CLIENTS; i++)
    {
        if (h_MainClass->Room->g_User[i].UID == UID)
        {
            UserNumber = i;
            break;
        }
    }

    if( h_MainClass->Room->g_User[UserNumber].IsFree == false && h_MainClass->Room->g_User[UserNumber].Secured == false)
        h_MainClass->Room->Kick(h_MainClass->Room->g_User[UserNumber].UID,"Didn't Authorized");

    return 0;
}

When ever this thread is created the program crashes and here is the exception:

First-chance exception at 0x00EC3548 in GGCRoomServer.exe: 0xC0000005: Access violation reading location 0x5D00009C.
Unhandled exception at 0x00EC3548 in GGCRoomServer.exe: 0xC0000005: Access violation reading location 0x5D00009C.
Was it helpful?

Solution

Create a heap variable to hold your data and pass that to the thread.

Secure * m_Secure = new Secure();
m_Secure->UID = g_User[PlayerNumber].UID;
m_Secure->MainClass = this;
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,m_Secure,NULL,NULL);

Get the data in the thread, and delete when done

RESULT WINAPI SecureThread(LPVOID Param)
{
    int UID = -1, UserNumber, i;

    Secure* m_Secure = (Secure*)Param;
....
    delete m_Secure;
    return 0;
}

OTHER TIPS

It looks like you are passing a local variable's address to a thread here

Secure m_Secure = {Room->g_User[PlayerNumber].UID,this};    
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,&m_Secure,NULL,NULL);

Being a local variable, m_Secure wil get out of scope and will be destroyed after the function finishes executing. Furtermore, m_Secure is likely created on the stack. Passing one thread's stack variable address to another is usually a bad idea
You need to create the variable on the heap
Something like

CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SecureThread,new Secure(...),NULL,NULL);
                                                            ^^^^^^^^^^^^^^

And don't forget to delete the pointer afterwards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top