views:

49

answers:

2

Hi!

This is the first time that i want to use threads, so i don't understand them fully for now.

I have two structures:

struct ddata  //difference content
{
    char *filename;
    char *size;
};
struct ddata *difference = (struct ddata *) malloc( dif * sizeof *difference );    

struct test
{
 struct ddata* difference;
 int diff;
};
struct test *MSG2;
MSG2 = (struct test*)malloc(sizeof(test)); 

MSG2->difference = difference;
MSG2->diff = diff;

I want to "send" the MSG2 two structure to my thread, and i did it this way:

CreateThread( 
        NULL,                   // default security attributes
        0,                      // use default stack size  
        CopyThread,       // thread function name
        &MSG2,          // argument to thread function 
        0,                      // use default creation flags 
        NULL); 

And now, here comes my problem. In my thread, i cast pParam back, and i want to print out some data to test it, but i am getting random characters. My thread:

DWORD WINAPI CopyThread( LPVOID pParam )
{
    char a[100];
    test *Test = (test*)(pParam);
     sprintf(a, "diff: %s", Test->difference->filename );
 MessageBoxA(NULL,a,0,0);
}

What i am doing wrong?

Thanks in advance!

kampi

+1  A: 

This is because CopyThread is expecting to receive a test* to the relevant data, but you are passing a test** - a pointer to the pointer to the relevant data. You then cast it to a test* in CopyThread, and this results in the random characters.

You should change your call to CreateThread to:

CreateThread( 
        NULL,                   // default security attributes
        0,                      // use default stack size  
        CopyThread,       // thread function name
        MSG2,          // argument to thread function 
        0,                      // use default creation flags 
        NULL); 
Michael
Yup, another void* victim. The pointer being out of scope by the time the thread starts could byte next, probably not.
Hans Passant
kampi
A: 

Hi!

I figured out what my problem was. When i declared my test structure i put an extra * there.

struct test 
{ 
  struct ddata* difference; 
  int diff; 
}; 
struct test *MSG2;  <-- here

If i remove the start, it is working fine:

struct test MSG2;

Thanks for your help!

kampi

kampi