Question 2
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
#include <string.h>
int main(void) {
char city[6];
strcpy(city, "Bengaluru");
printf("%s\n", city);
return 0;
}
- A strcpy needs a length
- B "Bengaluru" needs 10 bytes but city has 6, so strcpy writes past the array – a buffer overflow Correct
- C city must be a pointer
- D There is no bug
Correct Answer: Option B
strcpy never checks the destination size. Make the array large enough or use snprintf(city, sizeof city, "%s", src), which truncates safely.
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!