printf
/scanf
, not using any width for the format specifier %s
is vulnerable to buffer overflow CXX-S1004printf
or scanf
without width-limit on %s
70static void
71get_input_vector(char* input) {
72 printf("Enter the vector of the move (0=forward, 1=backward): ");
73 scanf("%s", input); 74
75 if (strlen(input) != 1) {
76 printf("Invalid input, please try again.\n");
printf
or scanf
without width-limit on %s
89get_input_action(char* input) {
90 printf("What do you want to do? (0: shoot, 1: move a ship) ");
91 /* TODO: use fgets instead of scanf */
92 scanf("%s", input); 93
94 if (strcmp(input, "0") != 0 && strcmp(input, "1") != 0) {
95 printf("Invalid input. Please try again.\n");
Using I/O operations such as printf
and scanf
without setting width limits for format strings can allow for buffer overflow when reading from a stdin pipe or writing to a stdout pipe.
You can limit the width for format strings by providing it between the %
and s
,
as the <width>
(any positive decimal integer).
Such as this: %<width>s
.
Limit the width of string specifiers by adding a maximum width for I/O operations, as outlined above.
char str[10];
scanf("%s", str);
char str[10];
scanf("%10s", str);