For an array of characters to be treated as a propper string, its last character must be a null terminator (or null byte) '\0'
.
The fgets
function, in particular always makes sure that this character is added to the char array, so for a size argument of 10
it stores the first 9 caracters in the array and a null byte in the last available space, if the input is larger than or equal to 9.
Be aware that the unread characters, like b
in your sample case, will remain in the input buffer stdin
, and can disrupt future input reads.
This null byte acts as a sentinel, and is used by functions like printf
to know where the string ends, needless to say that this character is not printable.
If you pass a non null terminated array of characters to printf
this will amount to undefined behavior.
Many other functions in the standard library (and others) rely on this to work properly so it's imperative that you make sure that all your strings are properly null terminated.