-2

I'm trying to run this file but it gives out this fault. Getting a segmentation fault (core dumped). Segmentation fault (core dumped) at pthread_join . Tried running printf at all the places and felt that this must be the error.

enter image description here

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <math.h>
#include <pthread.h>

float etime();
char *buffer;
void *foo(int kb)
{
    printf("Allocating memory\n");
    buffer = calloc(kb,sizeof(char));
    printf("Memory allocated\n");
    int i;
    printf("After i\n");
    for(i=0;i<kb;i++)
    {
        buffer[i]='z';
    }
    printf("End of for loop\n");
}
    
void et(int size)  
{
    
    int thrr;
    pthread_t num;
    etime();
    printf("Inside et \n");
    printf("Before calling create thread \n");
    thrr=pthread_create(&num,NULL,foo(size),NULL);
    printf("thrr = %d\n",thrr);
    if(thrr!=0)
    {
        printf("Cannot create thread!\n");
    
    }
    else
    {
        printf("Thread created successfully\n");
    
    }
    pthread_join(num,NULL);
    
    printf("Time taken = %f\n",etime());
}
    

  • 2
    `foo(size)`. Doesn't the compiler give you a warning for that? That parameter needs to be a function pointer and not the result of calling a function. And parameters are passed to the thread function via the last parameter in `pthread_create`. In summary, you are not calling `pthread_create` correctly and should review how to do that. – kaylum Feb 18 '21 at 20:21
  • 2
    Why is `foo()` declared to return a pointer when it has no `return` statement? – Barmar Feb 18 '21 at 20:25

1 Answers1

2

The signature for a pthread handler is void *handler(void *)

Switch from

void *foo(int kb)

to

void *foo(void *kb)

Call the handler using a pointer to the data:

thrr = pthread_create(&num, NULL, foo, &size);

Then, get the value of the passed int inside the handler:

void *foo(void *data)
{
    int kb = *(int *)data;

You also need to take care of size going out of scope, whenever is possible try to pass constant values, i.e.:

thrr = pthread_create(&num, NULL, foo, (void *)(uintptr_t)size);

then, in the handler:

void *foo(void *data)
{
    int kb = (int)(uintptr_t)data;

uintptr_t requires #include <inttypes.h>

David Ranieri
  • 39,972
  • 7
  • 52
  • 94