I'm confused how even though the char array mystring
I provided can only be upto 5 characters long, the length can exceed 5 if fgets
is supplied with a larger limit.
#include <stdio.h>
#include <string.h>
int main() {
char mystring[5];
fgets(mystring, 10, stdin);
printf("len: %d", strlen(mystring));
}
If I input 8 or more characters and press enter, the length of mystring
is 9. How does that happen considering the array mystring
's length is set to 5?
How does that happen considering the array mystring's length is set to 5?
Once the abstract state machine reaches an undefined behaviour, no further assumption about the continuation of the execution can be made.
See: Undefined, unspecified, and implementation-defined behaviour.
Consider:
// fgets(mystring, 10, stdin);
fgets(mystring, sizeof mystring, stdin);
Aside:
strlen()
returns a size_t
, not an int
. The call to printf()
invokes undefined behaviour as the format specifier doesn't match the corresponding argument.
// printf("len: %d", strlen(mystring));
printf("len: %zu", strlen(mystring));