Reputation: 113
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;
};
Upvotes: 2
Views: 1443
Reputation: 137547
....
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);
}
Upvotes: 10