So far in my program, I am dynamically allocating 4 matrices (in a way such that I can access an array member by arr[row][col]) and then filling them with some values (later to be multiplied with multi-threading). The program takes in 3 ints, n, m and p. Matrix A is n * m, B is m * p and C1/C are n * p. The problem I'm running into is that some inputs cause seg faults while others don't. For example, input 4 4 4 allocates and fills the array slots perfectly fine, but 5 5 5 gives me a seg fault when trying to access an array member in the fill portion of the code. Any help would be greatly appreciated.
#include <stdlib.h>
#include <stdio.h>
int **A;
int **B;
int **C1;
int **C;
void allocateMatrices(int n, int m, int p) {
int i, j;
/* Allocate n * m array */
A = malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
A[i] = malloc(m * sizeof(int));
}
/* Allocate m * p array */
B = malloc(m * sizeof(int));
for (i = 0; i < m; i++) {
B[i] = malloc(p * sizeof(int));
}
/* Allocate two n * p arrays */
C1 = malloc(n * sizeof(int));
C = malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
C[i] = malloc(p * sizeof(int));
C1[i] = malloc(p * sizeof(int));
}
/* Fill matrix A */
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
A[i][j] = i * j;
}
}
/* Fill matrix B */
for (i = 0; i < m; i++) {
for (j = 0; j < p; j++) {
B[i][j] = i + j;
}
}
}
int main() {
int n, m, p;
printf("Enter n (<=6000), m (<=3000), p (<=1000): ");
scanf("%d %d %d", &n, &m, &p);
allocateMatrices(n, m, p);
}