【问题标题】:pthread_join with a return value is giving segmentation fault带有返回值的 pthread_join 给出了分段错误
【发布时间】:2020-12-26 07:13:31
【问题描述】:

我正在尝试运行下面的代码,该代码使用 pthread_create 创建一个线程,并从线程内部返回计数。代码给了我一个分段错误

#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void *test_routine(void *arg);

int main(int argc, char **argv)
{
    pthread_t first_thread; 
    void *thread_return;
    int result = 0;
    
    result = pthread_create(&first_thread, NULL, test_routine, NULL);
    if (0 != result) 
    {
        fprintf(stderr, "Failed to create thread %s\n", strerror(result));
        exit(1);
    }
    
    result = pthread_join(first_thread, &thread_return);
    
    if (0 != result) {
        fprintf(stderr, "Failed to join a thread: %s\n", strerror(result));
        pthread_exit(NULL);
    }
    printf("\nValue returning from the test routine  %d\n", (int) thread_return);

   free(thread_return);
   exit(3);
}

void *test_routine(void *arg) 
{
    int count = 0;
    count++;
    pthread_exit(count);
}

【问题讨论】:

    标签: c pthreads posix pthread-join


    【解决方案1】:

    thread_return 不包含从malloc 返回的指针时,您正在将thread_return 传递给free。相反,它包含一个转换为指针的整数值。

    您应该只将malloc 返回的内容传递给free,因此请移除对free 的调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      相关资源
      最近更新 更多