What's the value of "size" going into this code?

Kent

Solved

Posted on 2011-10-12

Why do I get segmentation gault? in code attached.

```
Why do I get segmentation fault in foll code:
int i,j,k;
double **m1, **m2, **r;
**m1 = (double **)malloc(size * sizeof(double*));
**m2 = (double **)malloc(size * sizeof(double*));
**r = (double **)malloc(size * sizeof(double*));
for(i = 0; i < size; i++){
m1[i] = (double *)malloc(size * sizeof(double));
m2[i] = (double *)malloc(size * sizeof(double));
r[i] = (double *)malloc(size * sizeof(double));
}
while(size <=10)
{
size++;
for(i=0;i<size;i++){
for(j=0;j<size;j++)
m1[i][j] = 8.999;
}
```

14 Comments

Then look at the while() loop. You increment size and check the matrix as long as size is less than 10. Unfortunately, with only 5 items, you're over indexing the array(s).

kent

You probably want another variable to loop through the array using size as the upper limit, not 10.

Kent

int k=2, size=10;

while(k <= size)

{k++;

for(i=0;i<k;i++){

for(j=0;j<k;j++)

matrix1 i j = 6.908;

}

If you're trying to initialize all of the cells in the matrix to 8.99, it goes like this:

```
for (i = 0; i < size; ++i)
for (j = 0; j < size; ++j)
matrix[i][j] = 8.99;
```

Kent

Hi kites,

That's fine. But you need to confine the indexing into the matrix to the size of the matrix. Once you've got a matrix of 3x3, you can't index into row or column 4, 7, or 10. That's what your original code is doing.

Kent

Smthng like:

-10987777 -2877777

-10988770 -1233328

You're actually creating 3 matrices (m1, m2, and r) but you're only initializing m1.

Initialize all of them (or only create the ones that you want).

Kent

would be the first candidate for a segmentation fault. You're dereferencing an uninitialized pointer ... twice.

It should be :

m1 = (double **)malloc(size * sizeof(double*));

```
typedef struct tag_double_square_matrix
{
double * p;
int dim;
} DSM, *PDSM;
void DSM_INIT(PDSM pdsm, int sz, double d)
{
int i, n = sz * sz;
pdsm->p = malloc(sz * sz * sizeof(double));
pdsm->dim = sz;
for (i = 0; i < n; ++i)
*(psdm->p+i) = d;
}
double * DSM_GET(PDSM pdsm, int x, int y)
{
if (x < 0 || x >= pdsm->dim || y < 0 || y >= pdsm->dim)
return NULL;
return pdsm->p + (y * pdsm->dim) + x;
}
```

and more for setting values to a cell, or even resize a matrix.

Sara

Title | # Comments | Views | Activity |
---|---|---|---|

How to organize data in excel ? | 2 | 99 | |

Pointer in one class to member in another | 6 | 102 | |

Best UNIX-compatible free C compiler for Windows or Mac | 6 | 215 | |

Programming Arduino to control a Max7219 using C | 2 | 83 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**20** Experts available now in Live!