Segmentation fault when traversing an array in C

0

first of all I tell you that I already checked in 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 of Segmentation fault only occurs when the number of rows is equal to or greater than 5, when you will access the position 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;
    }
  } 
}
    
asked by isaac 13.11.2017 в 07:13
source

1 answer

1
matriz = (int**)malloc(filas*sizeof(int));

This reservation is, technically, incorrect. matriz is a double pointer, that is, matriz[i] points to a pointer ... and you are creating the reservation as if each element pointed directly to an integer.

Is it important? It can be vital for the proper functioning of your program:

  • In 32 bits, int typically occupies 32 bits, while int* usually occupies 32 bits ... in this case there would be no problem.
  • In 64 bits, int typically occupies 32 bits, while int* usually occupies 64 bits ... in this case the reservation made is just half of that required.

To avoid scares, try this:

matriz = (int**)malloc(filas*sizeof(int*));
//                                     ^ Importante!!!

And, now, please, avoid the use of global variables unless it is a requirement of the exercise ... you will save many scares.

    
answered by 13.11.2017 / 07:36
source