Calculate the sum of two numbers using the wire

advertisements

I have this little program I wrote to read two numbers from a user and calculate their sum using a thread function, which is also responsible for displaying the result on the screen.

int global[2];

void *sum_thread(void *arg)
{
    int *args_array;
    args_array = *(int**)arg;

    int n1,n2,sum;
    n1=args_array[0];
    n2=args_array[1];
    sum = n1+n2;

    printf("N1 + N2 = %d\n",sum);

    return NULL;
}

int main()
{
    printf("First number: ");
    scanf("%d",&global[0]);

    printf("Second number: ");
    scanf("%d",&global[1]);

    pthread_t tid_sum;
    pthread_create(&tid_sum,NULL,sum_thread,(void*)&global);
    pthread_join(tid_sum,NULL);

    return 0;
}

However, when I run the code, it does not work properly due to a segmentation fault. I suppose I am trying to access/use unallocated memory. Should I allocate it with malloc or is there other things I am doing wrong?


The name of the array, global points to the base address of the array. You can simply pass that and use the same inside your thread function.

However, just to mention a logical point, if you're passing global as a parameter to sum_thread() function, it need not be a global.

In your code, change

pthread_create(&tid_sum,NULL,sum_thread,(void*)&global);

to

pthread_create(&tid_sum,NULL,sum_thread,global);

Then, in sum_thread() function

args_array = *(int**)arg;

to

args_array = arg;