Reputation: 455
I'm trying to read a string via scanf
as follows:
char input[8];
scanf("%s",input);
It turns out that the program could read more than 8 characters. Say I inputed 123456789012345 and strlen(input) returns 15.
However when I set input as:
char input[4];
scanf("%s",input);
Inputing "12345" will cause '16146 segmentation fault'. Anyone knows how this happens?
Upvotes: 2
Views: 686
Reputation: 31296
Both are so called undefined behavior and should be avoided at all costs. No bugs are so tricky to find as those caused by this.
So why does this work? Well, that's the problem with undefined behavior. It may work. You have no guarantees at all.
Read more about UB here: Undefined, unspecified and implementation-defined behavior
Upvotes: 1
Reputation: 21532
Technically both cases invoke undefined behavior. That the first case happens to work on your system should not be taken to mean that your program is well-defined. Testing can only indicate the presence of bugs, not their absence.
Since you're still learning C I will take the opportunity to offer you advice for reading input from stdin
: always limit the length of input that will be read to the length of the buffer it's being read in to, reserving one spot at the end for the null-terminator.
If you want to use scanf
to read strings from stdin
, then it is safer to prefix the string format specifier with the maximum length of the string than to use a raw "%s"
. For example, if I had a char buffer[20];
that was the destination of a call to scanf
, I would use the format string "%19s"
.
Upvotes: 8