-4

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)

#include <stdio.h>

int main()
{

char characters;

printf("Input your characters: ");
scanf("%s", &characters);

FILE *fp = fopen("File.txt", "w");
fprintf(fp, "%s", characters);    
fclose(fp);

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
quantrillliam
  • 33
  • 1
  • 4
  • 3
    `char characters;` only stores one character. – Random Davis Nov 17 '16 at 17:22
  • 1
    I'm voting to close this question as off-topic because it's too basic. – slim Nov 17 '16 at 17:24
  • also this is a crash waiting to happen. You are smashing your stack by writing a random string over it – pm100 Nov 17 '16 at 17:24
  • @slim (I'm not defending the question, but..) are you sure that's a valid close reason? – Sourav Ghosh Nov 17 '16 at 17:29
  • 1
    @SouravGhosh this isn't the place for a meta-discussion, but on meta people are generally agreed that there are too many questions based on not knowing the basics, and since there's no ready-made close reason that matches, I've decided to do it this way from now on. SO isn't here for your first week of learning C. – slim Nov 17 '16 at 17:32

1 Answers1

1

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.

Quoting C11, chapter §7.21.6.2, fscanf(), (emphasis mine)

s Matches a sequence of non-white-space characters.286)

If no l length 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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • @DatBoi By either allocating the memory dynamically (which you can easily find out how to do online), or by defining a large char array. – Random Davis Nov 17 '16 at 17:29