I'm creating a program with multiple threads where one of threads creates 2 matrices based on input. These inputs are n and seed. Input specifies the square size of the matrix (n x n size) while seed fills the matrices with the values starting from seed incremementally. The problem I'm having is that this function runs fine for inputs n = 1,2,3,4 but 5 and above causes a segmentation fault.
void *creatematrices(void *arg)
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex3);
pthread_mutex_lock(&mutex4);
int seed;
printf("To create two nxn matrices, A and B,first please enter the value for n\n");
scanf("%d", &n);
printf("Now please enter the seed integer for the first element of matrix A\n");
scanf("%d", &seed);
A = (int**)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
A[i] = (int*)malloc(n * sizeof(int*));
}
B = (int**)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
B[i] = (int*)malloc(n * sizeof(int*));
}
C = (int**)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
C[i] = (int*)malloc(n * sizeof(int*));
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
A[i][j] = seed++;
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
B[i][j];
}
}
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
pthread_exit(0);
}
I'm using dynamic allocation for the 2d Arrays. I've realized this is probably a stack overflow error so I've already entered ulimit -s unlimited to no avail.
void* arg, among other things.pthread_create(&th1, &attr, creatematrices, NULL);is used to call it. If this were implemented not as a thread it would probably take the pointers A, B, and C as arguments.mallocbackwards. The firstmallocshould be allocating pointers usingsizeof(int*), and the secondmallocshould be allocating integers usingsizeof(int).