Harshit Jain - 1 year ago 101
C Question

# Segmentation fault in matrix multiplication using multiple threads

``````#include <stdio.h>
int arr[1000][1000];
int brr[1000][1000];
int h;
int f;
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo;
int sum = 0;
for(int i = 0; i < n; ++i)
{
sum += arr[x][i]*brr[x][f];
++f;
}
printf("%d\n", sum);
crr[x][h] = sum;
}
int main()
{
printf("Enter the value of m and n\n");
scanf("%d %d",&m,&n);
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
scanf("%d",&arr[i][j]);
}
}
printf("Enter the value of p and q\n");
scanf("%d %d",&p,&q);
if(p != n)
{
printf("The matrix multiplication is not possible\n");
return 0;
}
int* id;
id = (int *)malloc(4*sizeof(int));
for(int i = 0; i < p; ++i)
{
for(int j = 0; j < q; ++j)
{
scanf("%d",&brr[i][j]);
}
}
for(x = 0; x < m; ++x)
{
for(z = 0; z < q; z+=4)
{
f = z;
h = z;
for(int k = 0; k < 3; ++k)
{
}
for(int k = 0; k < 3; ++k)
{
}
}
}
for (int i = 0; i < m; ++i)
{
for(int j = 0; j < q; ++j)
{
printf("%d ",crr[i][j]);
}
printf("\n");
}
}
``````

The above program is supposed to multiply two matrix by multiplying row one of matrix by all the columns of other matrix using 3 threads and then row two by all the other columns and so on and then store the respective values int another matrix but it is giving segmentation fault. Where am I going wrong?

I think your problem is here:

``````pthread_create(&ar[k],NULL,BMM,NULL);
^^^^
void *arg is NULL
``````

and then:

``````void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo;             // Dereference NULL --> segmentation fault
``````

Further this looks strange:

``````void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo;           // ne is never used !!
int sum = 0;
for(int i = 0; i < n; ++i)  // Where does n come from ?
``````

Perhaps it should be `n` instead of `ne`?

If `n`, `x`, `f` and `h` are global variables you are into trouble as all threads will work on the same variables. That would be real bad. Each thread needs it own variables.

BTW:

Always check the value returned by `scanf` - something like:

``````if (scanf("%d %d",&m,&n) != 2)
{
``````if (scanf("%d",&arr[i][j]) != 1)