Pointer Value is changed when passed through Threadcreate

c++, multithreading, pointers

Solution

The code is printing the address of a pointer, not the address of the object. There are two pointer variables involved (one is declared in `main()` and the other is the argument of the thread function) so the output is different. Drop the `&`, address of operator, from the output statements:

cout << "Value of inst  "<<hex << inst << endl;

Give ownership of the supplied object to the thread as it knows when it has finished using it. In the posted code the object is deleted after the thread is created, possibly resulting in the thread using a dangling pointer. Move the delete of object from main into the thread.

The signature of the thread function is:

DWORD WINAPI ThreadProc(
  _In_  LPVOID lpParameter
);

and it must return a value, the posted code does not.

The code also has a resource leak as the handle returned from `CreateThread()` is not being closed. Either `CloseHandle()` immediately if the thread does not need to be joined with or store the thread handles, in a `std::vector` for example, to be joined with (using `WaitForSingleObject` for example) and closed later.

Problem

I am creating a new thread in which I am passing passing an object of class class demo is defined in .h file ``` int threadentry(void* data) { demo* inst=(demo*) data; cout << "Value of inst "<<hex << &inst<< endl;//value is different from below } int main() { while(1) { demo* inst=new demo(); cout << "Value of inst "<<hex << &inst<< endl; //value is coming different from above HANDLE threads; DWORD threadId1; if ((threads = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadentry, (void *)inst, 0, &threadId1)) == NULL) return -1; delete inst; system("pause"); } } ``` I think value should be different because address is copied in data variable of threadentry. How can I check that these are the same object passed.

Original source