Cannot pass string to receiver CreateThread

I have a stream function that looks something like this:

DWORD WINAPI Thread_ProcessFile( LPVOID lpParam )  {
 char *filename = (char*)lpParam;
 printf( "%s\n", filename );
}

      

I also have a class that calls CreateThread and uses the above function to address the subroutine:

void CMyClass::ProcessFile( void ) {
 HANDLE tHwnd = 0;
 char szBuffer[128];
 strcpy( szBuffer, "test_string" );

 tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)szBuffer, 0, NULL );  
 if ( tHwnd == NULL )
  return;
}

      

The problem is that the subroutine is getting / printing the garbage string and not the real thing (like a random set of characters, if any). If I do this, however:

tHwnd = CreateThread( NULL, 0, Thread_ProcessFile, (LPVOID)"test_string", 0, NULL );

      

the string is received and printed correctly. How can I build the string correctly and pass it to my thread function?

+2


source to share


2 answers


You are creating szBuffer on the stack. Therefore, by the time your thread started, ProcessFile () would have returned and the stack variable would have been freed. Hence, you get the garbage value. In the second case, you are passing a const string whose entry is probably in the read-only part of the process's memory and is not freed from the returned function (I don't think this is a guaranteed behavior, I wouldn't rely on that). This way you get the correct value in the function. You can allocate a string on the heap using the new [] and pass a pointer to the stream. Don't forget to remove the [] after the thread has finished processing.



+7


source


In your first case, the stack is declared szString

and so it is destroyed when the function ends and probably before the new thread has a chance to take over.



Use a variable with a longer lifetime, or something allocated on the heap (for example, with a new []) instead.

+2


source







All Articles