gets(s)
and scanf("%s", s)
are both unsafe and potentially incorrect because:
- with those calls as shown, there is no way for either function to determine the maximum number of characters to store into the array pointed to by
s
, hence overlong input will cause a buffer overrun leading to undefined behavior.
- in your case, it is even worse as
s
is an uninitialized pointer, so both functions would try a store data into a random address in memory causing undefined behavior in all cases.
gets()
cannot be used safely and has been deprecated in and then removed from the C Standard.
However, scanf()
can be given a limit with a numeric value between %
and s
:
#include <stdio.h>
#include <string.h>
char *read_string(void) {
char buf[100];
if (scanf("%99s", buf) == 1) {
printf("Your entered message is: %s\n", buf);
return strdup(buf); /* return an allocated copy of the input string */
} else {
/* no input, probably at end of file */
return NULL;
}
}
Note how only 99 characters can be stored into the array buf
to allow for the null byte terminator that marks the end of a C string. The %99s
conversion specification lets scanf()
store at most 100 bytes into buf
, including the '\0'
terminator.