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 ??