Question 5
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "hello world";
memcpy(text + 1, text, 5); /* shift right by one */
printf("%s\n", text);
return 0;
}
- A memcpy needs strlen
- B Source and destination overlap, which is undefined behaviour for memcpy – memmove must be used Correct
- C text is read-only
- D There is no bug
Correct Answer: Option B
Some memcpy implementations copy blocks forward or backward for speed, so the result can be wrong or (with sanitizers) the program is stopped. memmove(text + 1, text, 5) is correct.
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!