Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateThread() passing struct arguments weirdly

Tags:

c

windows

I'm passing a struct to CreateThread() function. The same code on another machine works fine. But on my machine, "SendItem" always becomes 0xccccccc Bad Ptr>. Does anyone know why?

....
myStruct mystruct; 
CreateThread(NULL, 0,  (LPTHREAD_START_ROUTINE)SendItem,(LPVOID)&mystruct, 0, &thread);
...

DWORD WINAPI SendItem(LPVOID lpParam)
{
    myStruct* SendItem= (myStruct*) lpParam;
    ...
}

struct myStruct
{
    char Name [256];
    int ID;
};
like image 584
Min Kim Avatar asked Dec 19 '25 16:12

Min Kim


1 Answers

....
myStruct mystruct; 
CreateThread(NULL, 0,  (LPTHREAD_START_ROUTINE)SendItem,(LPVOID)&mystruct, 0, &thread);
...

You're not showing the actual code, but this is presumably in a function somewhere.

You're passing the address of a local variable to your thread function. The problem is, that local variable is destroyed as soon as the containing function returns.

The solution is to allocate the object on the heap:

void start_thread(void)
{
    myStruct *mystruct = malloc(sizeof(*mystruct));
    if (!mystruct)
        return;

    CreateThread(NULL, 0,  (LPTHREAD_START_ROUTINE)SendItem, (LPVOID)mystruct, 0, &thread);
}
like image 180
Jonathon Reinhart Avatar answered Dec 22 '25 07:12

Jonathon Reinhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!