Problem with Segmentation Fault

Asked

Viewed 135 times

1

I’m creating a program that simulates a minefield, and option number 1 should take from a computer file an array (that contains points (where there is no bomb) and asterisks (where there is bomb) and copy to an array that I’m dynamically allocating in the reading function.

I’m having a problem Segmentation fault and I am not able to detect the error, I would be grateful for the help, follows below the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** leitura(char* nome)//Declaracao de funcao que aloca a matriz
{
    FILE* ponteiro;
    int i = 0,j = 1, k ,l;
    char** campo = NULL;
    char carac;

    ponteiro = fopen("nome", "w");

    while(!feof(ponteiro))
    {
        i++;
        campo = (char**) realloc(campo, i * sizeof(char*));     

        while(fscanf(ponteiro, "%c", &carac) != '\n')
        {
            campo[j - 1] = (char*) realloc(campo[j - 1], j * sizeof(char));
            campo[i - 1][j - 1] = carac;
            j++;    
        }
    }

    for(k = 0; k < i; k++)
    {
        for(l = 0; l < j; l++)
        {
            printf("%c", campo[i][j]);
        }
        printf("\n");
    }

    fclose(ponteiro);

    return campo; //Retorno da matriz alocada dinamicamente
}

int main (void)
{
    int tamanho = 0, linha = 0, coluna = 0;
    char* nome = NULL;
    char** retornoCampo = NULL;
    size_t tam;
    getline(&nome, &tam, stdin); //Funcao para adquirir o nome do arquivo
    int i, j;

    nome[strlen(nome) - 1] = '\0';

    int opcao = 0;

    scanf("%d", &opcao);

    switch(opcao) //Opcoes a serem escolhidas
    {
        case 1: //Leitura

            retornoCampo = leitura(nome);

            break;
        case 2: //Inicializacao do tabuleiro
            break;
        case 3: //Acao do usuario
            break;
    }

    return 0;
}
  • Here the code compiled and ran normally. The Segmentation fault only happens when I type a number/text and then type '1'. If I type '1' first and then insert a text/number, the program closes. Anyway, the program lets you write an option twice.

  • Here I reversed and continues with Segmentation fault

1 answer

0


I see two problems:

The first is in the various calls to the command realloc: when memory region size is increased, realloc does the copy of the memory that was already allocated to the new memory region (if this is effectively a new memory region), but does not boot the bytes that were allocated to more.

So, on the line: campo = (char**) realloc(campo, i * sizeof(char*)); a memory region of size is allocated sizeof(char*) (when i == 0), and this region contains memory junk, since you do not initialize it.

When the call campo[j - 1] = (char*) realloc(campo[j - 1], j * sizeof(char)); is executed, it attempts to relocate memory to a pointer that points to memory junk, thus causing segmentation failure.

Another problem occurs in sub-sequent line iterations:

campo[j - 1] = (char*) realloc(campo[j - 1], j * sizeof(char));

To facilitate the explanation, we will ignore the first problem, and pretend that the realloc will do the job right in the first problem raised.

When j == 1, campo[j - 1] will be allocated correctly with the size sizeof(char).

On the next line, just when j == 1, you make an assignment to the position [0][0] through the command: campo[i - 1][j - 1] = carac;, and then increases j.

In the second iteration (i == 1, j == 2), the realloc is done on the element campo[1], for j - 1 == 1. But note that the number of positions of the variable campo is still 1, and therefore only the index 0 is valid, causing again Segmentation fault. That is, you are resizing the wrong variable position campo. To solve this just change j for i in the line of this realloc, getting:

campo[i - 1] = (char*) realloc(campo[i - 1], j * sizeof(char));

I stress that these two problems occur simultaneously and should be corrected. Try to evidar realloc, he’s a very expensive command to run.

There may be other problems, but these were the ones I noticed most easily.

I hope I’ve helped, and I’m not too confused about the explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.