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