#include<stdio.h>
int main(void) {
char str[3];
scanf("%3s", str);
return 0;
}
What is the content of str[2] if I enter only one character? Is this undefined behaviour or will all remaining characters be fillt with '\0'? I do only care about the first three charaters. Even the \0 terminator is irrelivant to me because I do not want to use this array as a String.
I tried this and the remaining characters were all '\0' but this could be compiler specific.
The content would be indeterminate, since this is is a local array which was never initialized.
scanf(family) used with%3sonly guarantees that up to 3 characters are read - but if the user types for example a letter then a whitespace character,scanfwill stop there and only read the one character entered.It is also appending a null terminator character after the input, so in case the user types exactly 3 characters and then hit enter,
scanfwill write the null terminator out of bounds.You can try this yourself with this little program that prints the binary contents of the buffer:
Here I changed the size to 4 and initialized the array for illustration purposes.
Input:
A <enter>Output:
41 00 03 0441being the ASCII value of'A',00being the null terminator appended and03 04being the contents that happened to be in the memory since before. If this would have been an uninitialized local array, those values could have been "garbage". As we can see,scanfdoes not "zero pad" the remaining parts of the array (likestrncpywould do, for example).Input:
ABC <enter>Output:
41 42 43 0041 42 43are the letters and00is the appended null terminator. Had this been an array with size 3, it would have been out of bounds.scanfhas no clue how big the array is, so I would have lied toscanfif I used%3sand passed it achar [3]array, saying "hey you can store 3 characters + null termination here", even though there wouldn't be any room left.