1
votes

I am trying to run the code below which creates a thread using pthread_create, and returns the count from inside the thread. The code is giving me a segmentation fault

#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);
}
1

1 Answers

2
votes

You're passing thread_return to free when it doesn't contain a pointer returned from malloc. It instead contains an integer value that was converted to a pointer.

You should only pass to free what was returned from malloc, so remove the call to free.