Search code examples
cmatrixsegmentation-faultdynamic-memory-allocation

Segmentation error when changing values in a matrix


This is a matrix A which I am defining dynamically . Values of a and b is 9 so its a 9x9 matrix.

double **A = (double **) malloc(a * sizeof(double *));
    for (int i = 0; i < a; i++) {
      A[i] = (double *) malloc(b * sizeof(double ));
      }

Now when I am doing the following code , I get segmentation error . z=49 in this case

for(j=0; j<z; j++){
      for(i=0; i<z; i++){
          A[j][i]=1.0;
          }
          }

I tried changing the values of z and its working till z=30. I am loping over the columns and then loop over the rows and change the value for specific elements


Solution

  • You're allocating a data structure representing a 9 x 9 matrix. You're attempting to assign values as if it had dimensions (at least) 49 x 49. That grossly overruns the bounds of your object, producing undefined behavior. A segmentation fault / segmentation error is a common manifestation of undefined behavior arising from such a situation.

    That the UB manifests differently for z between 10 and 30 is irrelevant. In particular, if its manifestation happens to be consistent with your conclusion that "it works", that does not in any way mean that the program is correct or safe, nor does it say anything about how the UB should manifest for other values of z, or even that it should reliably manifest the same way for z in this range.