LearnFrenzy
Sign in Take a free test

C Library Functions · Find the Error · Question 5

Error: memcpy with overlapping regions Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links