scanf does not know how large the target buffer is. All he knows is the starting address of the buffer. C does not check boundaries, therefore, if you pass it a buffer address, the size of which should contain 2 characters, and you enter a string of 10 characters, scanf will write these additional 8 characters into memory after the end of the buffer.This is called buffer overflow, which is common malicious exploit. For some reason, six bytes immediately after your buffer are not βimportantβ, so you can enter up to 8 characters without visible obvious effects.
You can limit the number of characters read in a scanf call by including an explicit field width in the conversion specification:
scanf("%2s", A);
but you still need to make sure that the target buffer is large enough to accommodate this width. Unfortunately, there is no way to dynamically indicate the width of the field, as it is with printf :
printf("%*s", fieldWidth, string);
because %*s means something completely different in scanf (basically, skip the next line).
You can use sprintf to create your own format string:
sprintf(format, "%%%ds", max_bytes_in_A); scanf(format, A);
but you have to make sure that the format buffer is wide enough to hold the result, etc. etc. etc.
This is why I usually recommend fgets() for interactive input.
source share