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

2
  • if (argc != 3) ehhh? for a.out <integer value> ?? Commented Nov 28, 2016 at 8:17
  • to check if the number of argument more than 3 . Commented Nov 28, 2016 at 8:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.