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.
– regmoraes
Here I reversed and continues with Segmentation fault
– Gabriel Vinicius