Giving "Segmentation fault" when trying to open files in C

2

The following code gives me "Segmentation fault (core dumped)" when trying to open the file after declaration and filling a string with sprintf.

//Sem as duas seguintes linhas, o código roda normalmente
char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char *file1char;
int charnumber = 0;
while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
{   
    printf("%c\n", file1char[charnumber]);
}
pclose(File1);
return 0;
    
asked by anonymous 12.04.2018 / 14:18

2 answers

1

Your problem is related to memory allocation in C, you are inserting data into the char *file1char pointer that was not allocated, just declared.

Replace the char *file1char statement with char file1char[1024] , be aware that if your ref.fasta file is more than 1024 bytes, then memory corruption and possibly another sigsgv will occur.

Your code would look like this:

char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char file1char[1024];

int charnumber = 0;

while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
    printf("%c\n", file1char[charnumber]);

pclose(File1);

return 0;
    
12.04.2018 / 14:28
0

As I've already said, the problem is that you have not allocated any memory space for file1char.

You can also take a dynamic approach without much complication, being able to carry out the process in files of any size, since you get character by character:

char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char* file1char = calloc(1,sizeof(char)); //calloc é mais seguro que malloc

int charnumber = 0;

while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
{
    //"charnumber++" retorna o valor anterior de charnumber, e incrementa após retornar.
    printf("%c", file1char[charnumber++]);
    //Aumenta o tamanho de file1char dinâmicamente
    file1char = realloc(file1char,(charnumber+1)*sizeof(char));
}

fclose(File1);
free(file1char);

return 0;

But if you do not need this vector of characters to use for something later, there is no need to save the entire contents of the file to a string, you can only use one character and always assign it to it:

char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char file1char; //1 caracter

int charnumber = 0;

while(fscanf(File1, "%c", &file1char) != EOF) //Salva sobrescrevendo
    printf("%c", file1char);

fclose(File1);

return 0;
    
12.04.2018 / 14:51