简体   繁体   中英

Segmentation fault on 2D arrays of certain size

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 (nxn 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.

Presumably A is of int **A

then you made a mistake in the mallocs:

A = (int**)malloc(n * sizeof(int)); // << wrong. It has to be sizeof (int*)
for(int i = 0; i < n; i++)
{
   A[i] = (int*)malloc(n * sizeof(int*)); // << wrong. It has to be sizeof (int)
}

In the above A[i] points to a memory pool which contains n pointers to int, so it must be dealt accodingly.

Same story with all other allocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM