【问题标题】:Dangling pointer in pthread_join?pthread_join 中的悬空指针?
【发布时间】:2013-01-10 22:57:32
【问题描述】:

根据this,pthread_join 将输出参数**thread_return 设置为pd->result,然后释放pd。这没关系,我错过了什么,还是 glibc 中存在严重的错误?

    /* We mark the thread as terminated and as joined.  */
    pd->tid = -1;

    /* Store the return value if the caller is interested.  */
    if (thread_return != NULL)
      *thread_return = pd->result;


    /* Free the TCB.  */
    __free_tcb (pd);

【问题讨论】:

  • 请提供一个最小的、可编译的测试用例。

标签: c pthreads glibc memory-management


【解决方案1】:

__free_tbc 不会释放pd,而是释放线程的堆栈,即pd->tpp(另见here)。所以pd->result 在这些语句之后仍然是一个有效的指针。

【讨论】:

  • 谢谢。让我烦恼的另一件事是指针可能指向堆栈,但手册页明确警告它: retval 指向的值不应位于调用线程的堆栈上,因为该堆栈的内容在线程终止。 ( - 所以线程应该使用 malloc。)
  • @danuker:retval 指向的值可以是全局变量,也可以在堆上分配,因为pthread_join 会删除堆栈。 man 页面是对的。
猜你喜欢
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多