Question 3
Back to Exercise
The program below is given the input Alexander. Which statement correctly describes its bug?
#include <stdio.h>
int main(void) {
char name[5];
scanf("%s", name);
printf("Hello, %s\n", name);
return 0;
}
- A name needs an &
- B %s has no width, so the 9 letters plus '\0' are written past the end of the 5-byte array – a buffer overflow Correct
- C printf cannot print char arrays
- D There is no bug
Correct Answer: Option B
Limit the field to the array size minus one: scanf("%4s", name) – or better, read a line with fgets into a larger buffer.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!