Stefano Palmieri
Stefano Palmieri

Reputation: 13

Segmentation fault using threads in an elementary way

I'm doing a really easy program using pthreads but i keep getting a "Segmentation fault error" and I cannot understand why. The program is to be compiled in C language.

The program should create 3 threads, each of them should print its number and its calling thread number (in this case , i just want 3 threads to say "I'm thread (i) and the calling thread is 0 " since they are all created from the same thread)

The problem, I think, is with the malloc function used to allocate memory to be passed.

In case this is te problem, how can i solve it?

Should I create an array of 3 pointers before the "for" loop, and store in each pointer of this array the two variables i want to pass to the thread? How to actualy do it? I tried but it doesn't seem to work.

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

void *Son (void* arg)
{int *id=(int*)arg; //retrieve array
  sleep(id[1]+1);
  printf("I'm thread %d , created from %d! \n",id[1],id[0]);

free(arg);
 pthread_exit(0);
}




int main()
{pthread_t threads[3];
 int i;
 for (i=0;i<3;i++)
    {int *a= malloc(2*sizeof(int)); // dynamically allocate a variable which will be freed in the thread once executed
    a[0]=0;  //store i in the content of dynamically allocated a
    a[1]=i;
    pthread_create(&threads[i],NULL,Son ,(void*)a);
    }
int j;
for (j=0;j<3;i++)
    {pthread_join(threads[i],NULL);
    printf("Joined thread %d",j);
    }
printf("THREAD FINISHED\n");
return 0;
}

Upvotes: 0

Views: 150

Answers (1)

Spikatrix
Spikatrix

Reputation: 20252

Here:

for (j=0;j<3;i++)
{
    pthread_join(threads[i],NULL);
    printf("Joined thread %d",j);
}

you probably wanted to use threads[j] instead of threads[i]. i, at this point is 4 and you are accessing an invalid memory address via the pthread_join. Also, you need to use j++ instead of i++.

Upvotes: 4

Related Questions