【问题标题】:Extremely simple mutex code gives a segmentation fault极其简单的互斥代码给出了分段错误
【发布时间】:2022-12-18 11:40:42
【问题描述】:

已解决 07/12另一个文件是这里的罪魁祸首!

问题这个非常短的 Mutex 代码似乎在 .见下图:

下面提供了复制此问题的代码:

struct test_struct {

    pthread_mutex_t test_lock;

} *test_ptr;

void test(){

    test_ptr = malloc(sizeof(struct test_struct));
    pthread_mutex_init(&test_ptr->test_lock, NULL);
    pthread_mutex_lock(&test_ptr->test_lock);
    fprintf(stderr, "Reached here\n");
    return;
}

int main(int argc, char *argv[])
{
    test();
    return 0;

}

我还尝试了什么?

  • 我已将互斥锁设为全局变量(无结构)
  • 我已将互斥量作为测试函数的一部分 ()

【问题讨论】:

  • 无法重现,它工作正常并打印Reached here,问题一定出在其他地方。
  • 您是否包括了所有必需的标头?使用不带标头的 malloc 可能会导致奇怪的事情发生。
  • 已解决:框架中有另一个文件定义了 pthread_mutex_init 和 pthread_mutex_lock。所以,以上是行不通的。我很抱歉不必要地占用大家的时间:(
  • 您应该检查 malloc 的返回值是否为 NULL

标签: c memory-management segmentation-fault mutex


【解决方案1】:

你使用的是动态内存,使用后需要删除。 免费(测试指针);

【讨论】:

  • 这是正确的,但与所讨论的问题无关。这应该是评论,而不是答案。
【解决方案2】:

在测试函数中你需要锁定和解锁互斥量,在主函数中只需给出 pthread_mutex_init(&test_ptr, NULL);。 最后销毁互斥量 pthread_mutex_destroy(&test_ptr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多