I have set the size of the string word
to 5. I am taking input with scanf()
and the format specifier is %s
. Though the size of the string is 5 but if I enter a larger string than the length 5 it is also taking the whole input. Why this is happening?
Here is my C program:
#include <stdio.h>
#include <string.h>
int main() {
char word[5];
printf("Enter word: ");
scanf("%s", word);
printf("Word: %s\n", word);
strlwr(word);
printf("To Lower: %s\n", word);
return 0;
}
If I enter AbcDEfghij
which length is 10 but it will take this and print the full string correctly. How can I prevent this? I want not to take input larger than the size.
CodePudding user response:
C doesn't perform bounds checking on arrays. That's part of what makes it fast. However, that also means that it will allow you to do things you aren't supposed to like writing past the bounds of an array. When you do that, you trigger undefined behavior.
When your program has undefined behavior, it could crash, it could give strange results, or it could (as in your case) appear to work properly. What's worse, a seemingly unrelated change such as adding an unused local variable or adding a printf
call to debug can change how undefined behavior manifests itself.
So to summarize, the language trusts you to not do things you're not supposed to.
CodePudding user response:
You are seeing buffer overflow. In C a string is represented as an array of one byte characters, terminated by a NULL character. scanf has no idea how large your buffer is, and will happily copy any input into it. This vulnerablity leads to a class of security flaws called buffer overflow attacks. This can lead to interesting results such as this example, which is set up to take 123456 as input, you will overflow your character array and it should output the value 54, corresponding to the Ascii code for 6.
#include <stdio.h>
#include <stdint.h>
struct overflow_test{
char buffer[5];
uint8_t number;
};
int main()
{
struct overflow_test s;
s.number=6;
printf("%d\n", s.number);
printf("\n");
scanf("%s", &s.buffer);
printf("%d\n", s.number);
return 0;
}
It is your responsibility to make sure you do not take in more characters than your buffer can hold. To avoid this issue, you can use a function like fgets instead, which takes in a maximum number of characters so that you don't overflow your buffer.