2

I tried to run this code in terminal in osx and linux ubuntu :

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int fact=1; //this data is shared by thread(s)
int n;
int x;
int *arrayName;

int main(int argc, char *argv[])
{

    if (argc != 3){ //check number of arguments
        printf("Must use: a.out <integer value>\n");
        return -1;
    }
    int x = atoi(argv[1]);
    n = atoi(argv[2]);
    if (n < 0){ //check second passed argument
        printf("%d Must be >=0\n", atoi(argv[2]));
        return -1;
    }
   arrayName = (int *) malloc(n * sizeof(int));
    pthread_t tid[n];

    for(int i=0;i<n;i++){
        pthread_create(&tid[i], NULL, (void *) i, NULL);
    }
    int i=0;
    while(i<n){
        pthread_join(tid[i],NULL);
        i++;
    }
    i=0;
    while (i<n) {
        printf("Thread is %d",arrayName[i]);
        i++;
    }
}
void *calculateMult(void *i) {
    int j = (int) i;
    arrayName[j] = x * j;
    return NULL;
};

I ran these commands in terminal :

cc -pthread main.c

./a.out 1 1

But it gives me segment fault : 11 in osx and segment fault (core dumped) in linux , WHY ??

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

1

I think you need to change pthread_create call because you have passed the wrong argument in pthread_create. Also check return from pthread_create.

You need to something like this

int s = pthread_create(&tid[i], NULL, (void *)calculateMult,  (void *)&i);
if (s != 0)
       printf("pthread_create failed");

Also you need to change your function as:

void *calculateMult(void *i) {
    int *j = (int*) i;
    arrayName[*j] = x * (*j);
    return NULL;
};

so you are done.

Mohan
  • 1,871
  • 21
  • 34
0

In your code, you're calling

 pthread_create(&tid[i], NULL, (void *) i, NULL);

where, the third argument i is an int but the expected argument is of type void *(*start_routine) (void *). This invokes undefined behavior.

You need to supply a function pointer, something like calculateMult or alike.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261