First of all I tell you that I already checked the forum about the error and I did not find the solution or the explanation of why this error is generated. I have the following code that creates an array with the sizes entered by the user, the error Segmentation fault
only occurs when the number of rows is equal to or greater than 5, when the position is going to be accessed matriz[4][0]
is when the error occurs.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int filas = 0;
int columnas = 0;
int **matriz = NULL;
int main(){
inicializarMatriz();
return 0;
}
void inicializarMatriz(){
printf("Ingrese el número de filas: ");
scanf("%d", &filas);
printf("Ingrese el número de columnas: ");
scanf("%d", &columnas);
//Se asigna a la matriz el número de filas ingresado
matriz = (int**)malloc(filas*sizeof(int));
//Se asignan a la matriz las columnas por cada fila
for(int i=0; i < filas; i++){
matriz[ i ]= (int*)malloc(columnas*sizeof(int));
}
//Se solicita llenar la matriz
for(int f = 0; f < filas; f++){
for(int c = 0; c < columnas; c++ ){
//printf("Ingrese el valor para la posición [%d][%d]: ", f, c);
//scanf("%d",&matriz[f][c]);
matriz[f][c] = 0;
}
}
}
This reservation is technically incorrect.
matriz
it's a double pointer, that is, itmatriz[i]
points to a pointer... and you're creating the pool as if each element points directly to an integer.It is important? It can be vital for the proper functioning of your program:
int
it typically takes up 32 bits, while itint*
usually takes up 32 bits... in this case there would be no problem.int
it typically occupies 32 bits, while itint*
usually occupies 64 bits... in this case the reservation made is exactly half of what is required.To avoid scares try like this:
And, for that matter, please, avoid the use of global variables unless it is a requirement of the exercise... you will save yourself a lot of scares.