Click to See Complete Forum and Search --> : Whatis wrong with my multithreading program?


dullboy
May 11th, 2006, 08:29 AM
Here is my code.


// C++ server
typedef struct tagData
{
char* s;
int* pX;
}data;

void func2(LPVOID item)
{
data* pData = (data*)item;

*(pData->pX) = 9;
pData->s = "test";
}

void __declspec(dllexport) func(char* str, int& x)
{
data* pData = new data;
pData->s = str;
pData->pX = &x;

_beginthread(func2,0,pData);

}

// C++ Client

int main(int argc, char* argv[])
{
char* str = new char[100];
str = " ";
int x;


func(str, x);
MessageBox(NULL,NULL,str,MB_OK);
char s[30];
sprintf(s,"x=%d",x);
MessageBox(NULL,NULL,s,MB_OK);
return 0;
}


Actually, I am able to get the modified integer x but I couldn't get the modified string str from my C++ client. Can any guru help me how to fix the problem? Thanks so much in advance.

wildfrog
May 11th, 2006, 09:10 AM
Déjà Vu.

use strcpy(...) or on of it equivalents when you copying a c-string from one buffer into another.


char *psz = new char[256];
psz = " "; // this is wrong!

// do this
char *psz = new char[256];
strcpy(psz, " ");
delete[] psz;


- petter

dullboy
May 11th, 2006, 09:39 AM
Thanks for pointing out it. But can you also advise me how to fix the problem why I couldn't get the modified string in my C++ client?
Déjà Vu.

use strcpy(...) or on of it equivalents when you copying a c-string from one buffer into another.


char *psz = new char[256];
psz = " "; // this is wrong!

// do this
char *psz = new char[256];
strcpy(psz, " ");
delete[] psz;


- petter

wildfrog
May 11th, 2006, 09:51 AM
Thanks for pointing out it. But can you also advise me how to fix the problem why I couldn't get the modified string in my C++ client? I believe I just did ;) .


void __declspec(dllexport) func(char* str, int& x)
{
data* pData = new data;
pData->s = str; // now pData.s points to the same memory location as str.
pData->pX = &x;

_beginthread(func2,0,pData);

}

void func2(LPVOID item)
{
data* pData = (data*)item;

*(pData->pX) = 9;
pData->s = "test";
// now pData.s points to "test", but this doesn't affect str.
// Use strcpy to copy "test" into the buffer that pData.s is pointing to,
// which happens to be the same buffer as str is pointing to.
}

- petter