带返回值的pthread_join给出分段错误

问题描述

我正在尝试运行下面的代码,该代码使用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);
}

解决方法

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

您应仅将malloc返回的内容传递给free,因此请删除对//assuming you malloc'd the table somewhere before calling this... void nodecreate() { char line[MAXLENGHT]; scanf("%d",table->rowsNumber); node->array = malloc(sizeof(char*)*table->rowsNumber); for(i=0;i<table->rowsNumber,i++){ fgets(line,MAXLENGHT,stdin); node->array[i]=malloc(strlen(line)*sizeof(char)); strcpy(node->array[i],line); } //don't forget to free both every char * and the char ** somewhere... 的呼叫。