views:

164

answers:

2

I have a thread 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 for the routine address:

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 routine is receiving/printing a garbage string and not the real thing (eg. 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 properly build a string and pass it to my thread function?

+2  A: 

In your first case, szString is declared on the stack, and so it's destroyed when the function ends and likely before the new thread has a chance to take over.

Instead, use a variable with a longer lifetime, or something allocated on the heap (e.g., with new[]).

greyfade
+5  A: 

You are creating the szBuffer on the stack. Hence by the time your thread starts, the ProcessFile() function would have returned and the stack variable would have been deallocated. Hence you are getting the garbage value. In the second case, you are passing a const-string which post probably resides in the read-only part of the process memory and is not deallocated on the function return (I don't think this is the guaranteed behavior, I wouldn't rely on it). So you are getting proper value in the function. You can allocate the string on the heap using new[] and pass the pointer to the thread. Don't forget to to delete[] once the processing is completed in the thread.

Naveen
Ha, that's a pretty cool "gotcha!" I didn't even think about. Creating the string using the new operator worked perfectly. Thanks, guys!
slkandy