I writing a C code to read a .txt file, however I keep having this segmantation fault and I can't figure out what is going on, Could i please use some help?
Here's the code. More information below.
#include <stdlib.h>
#include <stdio.h>
#define MAX 256
int lerArq(int **I, char filename[MAX],int *h,int *w);
int main(){
char option;
char filename[MAX];
int *h,*w;
int **I;
int i,j;
printf("Q Quit (terminar o programa) \n L Ler um arquivo de imagens \n S Salvar a imagem em arquivo \n M Manter a imagem-entrada anterior \n B Binarizar a imagem-entrada \n C Calcular Contorno da imagem-entrada \n F Filtrar a imagem-entrada \n I Inverter a imagem-entrada \n R Rotular a imagem-entrada \n");
printf("Digite a opção: \n");
scanf("%c", &option);
if(option=='l' || option=='L'){
printf("Digite o nome do aquivo: \n");
scanf("%s", filename);
lerArq(I,filename,h,w);
}
return 0;
}
int lerArq(int **I, char filename[MAX],int *h,int *w){
FILE *arq;
arq=fopen(filename, "r");
char line[5];
int i,j;
if(arq == NULL) {
printf("ERRO: Não foi possível localizar o arquivo: %s! \n", filename);
return 0;
}
fscanf(arq, "%s", line);
fscanf(arq, "%d %d", w, h);
fscanf(arq, "%s", line);
printf("%d %d", *h, *w);
fclose(arq);
return 1;
}
The file that I am opening has the following aspect: The first and third line are irrelevant at this moment, they are only representing the format of the image(this file represents a black and white image). The second line, represents the number of rows and columns of the matrix.
Turns out that when I try to print the number of rows and columns, i get this error, segmentation fault.
P2
10 10
255
0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 1 1 1 0
1 1 0 0 1 0 0 1 1 0
0 0 1 0 0 1 0 0 1 0
0 0 1 0 0 1 0 0 1 0
0 0 0 1 0 1 0 0 1 0
0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0
CodePudding user response:
int *h,*w;
h
and w
are indeterminate, they do not point to anything meaningful. Indeterminate pointers lead to undefined behaviour.
You could instead declare them as:
int h, w;
And then pass them to the letArq
as:
lerArq(I, filename, &h, &w);
Or instead declare them where needed.
Side-notes: I
is an unused parameter.
scanf
and fscanf
returns something, check for it.
return 0
and return 1
are equivalent to return EXIT_SUCCESS
and return EXIT_FAILURE
respectively.
The return value of letArq
goes unused.