I'm trying to put and get+print four char characters in a file by promting the user for four chars. However, there is an error (Fatal error: glibc detected an invalid stdio handle).
After debugging I found the fault at the line fputc(c[3], putc)
. After prompting the user for the fourth time, it cannot put the fourth char c[3] in the file.
Please help me to understand.
Here's my code:
FILE* putc = fopen("test3.txt", "w");
if(putc == NULL)
{
return 1;
}
char c[4];
for(int i = 0; i < 4; i++)
{
printf("char: ");
scanf("%s", &c[i]);
fputc(c[i], putc);
}
fclose(putc);
FILE* getc = fopen("test3.txt", "r");
if(getc == NULL)
{
return 1;
}
char abc;
while ((abc = fgetc(getc)) != EOF)
{
printf("%c", abc);
}
printf("\n");
fclose(getc);
scanf("%s", &c[i])
writes a null character after the input it reads and stores. c
is defined with only four elements, so, when i
is three, the null character is written outside of the array c
, corrupting other memory in the program.
One fix is to make c
larger and scan with scanf("%1s", &c[i])
.
Another is to scan with scanf(" %c", &c[i])
, to skip spaces and read a single character, which is put into c[i]
with no terminating null character.