user2824843
user2824843

Reputation: 43

Segmentation fault on initializing a 2D array

I've checked that my code is properly carving out memory space, but as soon as I try to initialize my 2D array to some values and then sum up the values, I receive a segmentation fault on just a 2x2 array. I would like to eventually scale my code up to a much larger array, but I can't even get it working here. I know there are many posts about segmentation fault regarding malloc and 2D arrays, but I've been unable to find one that helps me with my problems since my C knowledge is just beginning. Any help that you can give or if you can point me to a previous question would be greatly appreciated. Thank you!

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main()
{
  double sum=0;
  int i,j;
  int N = 2;

  double **array;
  array = malloc(N * sizeof(double *));

 if(array == NULL) printf("Failure to allocate memory.\n");

 for(i=0; i<=N; i++)
    {
      array[i] = malloc(N * sizeof(double));
      if(array[i] == NULL) {
     printf("Failed to allocate memory for arr[%d].\n", i);
     exit(0);
     }
     }

 for(i=0; i<=N; i++)
  {
    for(j=0; j<=N; j++)
  {
    array[i][j] = 1.0/(i+j);
    sum = sum + array[i][j];
   }
   }

   return(0);
 }

Upvotes: 3

Views: 2880

Answers (2)

memo1288
memo1288

Reputation: 738

You're allocating space for an NxN array, but in your for cycles, you're trying to access an (N+1) by (N+1) array. You can replace your cycles by one of the following:

for(i=0; i<N; i++)

or

for(i=1; i<=N; i++)

Given that you are calculating 1.0/(i+j), you may use the second one, because the first will produce a division by zero when i=0, j=0. But beware, if you use the second option you should shift your indexes by 1, like this: array[i-1][j-1], because these will always start at 0. It is better to use the first option.

Upvotes: 3

Andrew Cottrell
Andrew Cottrell

Reputation: 3413

You've fallen victim to one of the classic blunders: Using <= instead of < .

for(i=0; i<=N; i++)

That will initialize array[0], array[1], and MOST IMPORTANTLY array[2] (because 2 <= 2), but you didn't malloc space for three pointers, only two.

Here's what you want:

for(i=0; i<N; i++)

It will iterate through array[0] and array[1] (for a total of two entries).

(Not saying you don't have other bugs, but that's definitely one of them.)

Upvotes: 6

Related Questions