Giving "Segmentation fault" when I try to open C files

Asked

Viewed 303 times

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;

2 answers

2


Your problem is related to memory allocation in C, Voce is inserting data in pointer char *file1char not allocated, only declared.

Replace the declaration char *file1char for char file1char[1024], take care because if your file ref.fasta has more than 1024 bytes will happen memory invasion and possibly other sigsegv.

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;

0

As already answered here, the problem is that you have not allocated any memory space to file1char.

You can also take a dynamic approach without too 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 don’t need this array of characters to use on something later, there is no need to save all the file contents in a string, you can use only 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;

Browser other questions tagged

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