【问题标题】:After casting pParam, why do I get random characters back?施放 pParam 后,为什么我会得到随机字符?
【发布时间】:2010-02-16 23:52:15
【问题描述】:

这是我第一次使用线程,所以我暂时不完全了解它们。

我有两个结构:

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;

我想将 MSG2 两个结构“发送”到我的线程,我是这样做的:

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); 

现在,我的问题来了。在我的线程中,我将 pParam 回退,我想打印出一些数据来测试它,但我得到的是随机字符。 我的主题:

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

我做错了什么?

提前致谢!

坎皮

【问题讨论】:

    标签: c windows mfc multithreading


    【解决方案1】:

    这是因为 CopyThread 期望接收对相关数据的测试*,但您正在传递测试** - 指向相关数据的指针的指针。然后将其转换为 CopyThread 中的 test*,这会产生随机字符。

    您应该将对 CreateThread 的调用更改为:

    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); 
    

    【讨论】:

    • 是的,另一个 void* 受害者。到线程启动时指针超出范围可能是下一个字节,可能不会。
    • 嗨!如果我在 MSG2 之前删除“&”,那么我的应用程序就会冻结:(
    【解决方案2】:

    我知道我的问题是什么。当我声明我的测试结构时,我在其中添加了一个额外的 *。

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

    如果我删除开始,它工作正常:

    struct test MSG2;
    

    感谢您的帮助!

    坎皮

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2015-06-20
      • 2013-07-06
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多