简体   繁体   中英

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);
 }

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.)

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.

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