Home > Mobile >  Segmentation Default (Double Pointer/structs)
Segmentation Default (Double Pointer/structs)

Time:10-19

I'm having a segmentation fault on the following code. It's a C project for the university. The purpose of this code is to read data from an input file, and place it into a 2D array created with a double pointer. In other words, in the first "for cycle" I will read 3 integers: the row, the column and the value. For example, 3 3 2, is row 3, column 3, value 2.

void cria_mapa(FILE *InputFile1, FILE *OutputFile, labirinto_struct *labirinto){

   int i=0, k=0;
   int linha,coluna,valor=0;

   labirinto->map = (int **) malloc(labirinto->num_linhas*sizeof(int *));

   if( labirinto-> map == NULL){
        exit(0);
    }

     for(i=0;i<labirinto->num_linhas;i  ){
     labirinto->map[i] = (int *) calloc(labirinto->num_colunas, sizeof(int));
   }

    for(k=0;k<labirinto->num_paredes;k  ){
       if(fscanf(InputFile1, "%d %d %d", &linha, &coluna, &valor)!=3){
            exit(0);
       }

       labirinto->map[linha][coluna]=valor;

       fprintf(OutputFile, "%d %d %d\n", linha, coluna, labirinto->map[linha][coluna]);

   }
   return;
}

and I have a struct:

typedef struct _labirinto_struct
{
    int num_linhas, num_colunas, num_paredes;
    int Pxi, Pyi, Px2, Py2;
    char letra;
    int variante;
    int **map;   

}labirinto_struct;
void free_mapa(labirinto_struct *labirinto){

    int i=0;

    for(i=0;i<labirinto->num_linhas;i  ){
     free(labirinto->map[i]);
   }


    free(labirinto->map);

   return;

}

CodePudding user response:

The code, allocations and deallocations, looks good so far.

But you should check the values read:

if (fscanf(InputFile1, "%d %d %d", &linha, &coluna, &valor)!=3) {
    exit(0);
}

if (linha >= labirinto->num_linhas) {
    fprintf(stderr, "linha overflow: %d vs %d\n", linha, labirinto->num_linhas);
    exit(1);
}

if (coluna >= labirinto->num_colunas) {
    fprintf(stderr, " overflow: %d vs %d\n", coluna, labirinto->num_colunas);
    exit(1);
}

labirinto->map[linha][coluna]=valor;

I would guess, that the lines and columns given start at 1 up to max and not 0 to max - 1.

  •  Tags:  
  • c
  • Related