0

I have a sample weird code like this:

#include<stdio.h>

int main(){

    int t;
    scanf("%d", &t);

    while(t--){
        char s[1];
        scanf("%s", s);     
    }
}

I have test that if I have t from input that > 1 ( like t = 3) then put a single character to s, then the program ends, while t hasn't downed to 0 yet. Could anyone explain for me what happens here. Thanks for your help!

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

Change char s[1]; to char s[100]; or other length to allow at least as many characters as you will enter plus one for the terminating null character.

When scanf processes a %s, it appends a terminating null character to the end of the characters it matches to the %s. Since you declared s as char s[1];, there is no reserved room for the terminating null character, and scanf attempts to write beyond the reserved space.

Then the behavior of your program is not defined by the C standard.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • But what about when I initialize a string like char a[9] = "123456789", then the compiler got me compile error, although this string is not from user input, which couldn't lead to the null character at the last position. – Nguyễn Tùng Dương Dec 22 '22 at 18:28
  • 1
    a[9] = "123456789"; is 10 characters (there's a null at the end which you can't see) but you only allocated 9 chars. – Humpity Dec 22 '22 at 18:36
  • 1
    @NguyễnTùngDương: If the compiler warns you about `char a[9] = "123456789";`, you are probably compiling as C++, not C. C++ is a different language with different rules. In C, when initializing an array of characters with a string, the compiler will allow an array with only room for the character in the string, without the terminating null character. If there is room for the terminating null character, it includes it. If there is not, it does not include it. In C++, the rule is that there should be room in the array for the terminating null character. – Eric Postpischil Dec 22 '22 at 18:41