I have the following code, and I keep on getting the "Program has stopped working" error after I have input the characters.
I have done some debugging and found that the issue is in the writing to the file part, however I cannot find the issue.
Can anyone help me? (I'm new to C)
printf("Input your characters: ");
FILE *fp = fopen("File.txt", "w");
fprintf(fp, "%s", characters);
In your code,
characters is of type
char which is not fit to store a string. You need to make
characters as an array.
Essentially, what happens behind the hood is, because of
%s, the input value (even if a single
char) gets stored in the memory pointed by the address supplied, but after that, the attempt to store the terminating null, causes out of bound access. This invokes undefined behavior.
C11, chapter §220.127.116.11,
fscanf(), (emphasis mine)
sMatches a sequence of non-white-space characters.286)
llength modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.