# Why am I getting Segmentation fault dynamic array?

## Question:

They say not to cast the return of the `malloc` function, but this code, if the dimension of the matrix is ​​above 4, gives segmentation fault from `matriz` in the count:

``````int main(){

int tamanho = 5;

float **matriz = malloc(tamanho * sizeof(float));

for(int i=0; i<tamanho; i++)
*(matriz + i) = malloc(tamanho * sizeof(float));

for(int i=0; i<tamanho; i++){
for(int j=0; j<tamanho; j++){
scanf("%f", &matriz[i][j]);
}
}
}
``````

Now if I cast, then it works great. But why? If they say they can't…

Note this line:

``````float **matriz = malloc(tamanho * sizeof(float));
``````

Considering `tamanho` is 5 and `sizeof(float)` is 4, this would be:

``````float **matriz = malloc(20);
``````

And so here, we have this:

``````for(int i=0; i<tamanho; i++)
*(matriz + i) = malloc(tamanho * sizeof(float));
``````

You use `*(matriz + i)` , that is, you are adding an integer with a pointer, which is not a good idea. This then takes the value of the address and adds to it the value of `i` multiplied by the size of the type referenced by the pointer, which is `float *` . Assuming the size of the pointer is 8 bytes, this will access positions, 0, 8, 16, 24 and 32. When accessing positions 24 and 32 (and half of the area of ​​16), you will be writing in an area of unallocated memory, which can give segmentation fault .

The problem is that you allocated the wrong-sized array because it is an array of pointers, not an array of `float` s. That is, instead:

``````float **matriz = malloc(tamanho * sizeof(float));
``````

Should have put this (note the extra `*` ):

``````float **matriz = malloc(tamanho * sizeof(float *));
``````

And that makes all the difference since `sizeof(float)` is 4 while `sizeof(float *)` is 8.

Also, I recommend rewriting this:

``````    *(matriz + i) = malloc(tamanho * sizeof(float));
``````

So:

``````    matriz[i] = malloc(tamanho * sizeof(float));
``````
Scroll to Top