Why am I getting Segmentation fault dynamic array?

3

They say not to cast on the return of the malloc function, but this code there if the array dimension is greater than 4, gives segmentation fault from matriz[5][1] in the count: / p>

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, it works fine. But why? If they say they can not ...

    
asked by anonymous 30.09.2016 / 22:32

2 answers

6

Look at this line:

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

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

float **matriz = malloc(20);

And so here we have it:

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

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

The problem is that you have 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 * more):

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

And this makes all difference since sizeof(float) is 4 while sizeof(float *) is 8.

And also, I recommend rewriting this:

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

So:

    matriz[i] = malloc(tamanho * sizeof(float));
    
30.09.2016 / 22:42
2

In short:

this line

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

is wrong, should look like this:

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

One thing that most beginners can not understand is that there are no "arrays" in C, what looks like an "array" is actually an array of pointers.

    
01.10.2016 / 01:42