1

If I have an array of elements, is it okay to use memcpy to copy some data from the back of an array to the front part

Presented in code:

int a[5] = {1,2,3,4,5};

memcpy(a, a + 2, 3 * sizeof(int));

As you can see some parts are copied to the other place in the front and then overwritten later (number 3).

Array after memcpy is {3, 4, 5, 4, 5}, but does this invoke undefined behaviour or is it completely valid to do such thing? I'm using c++ and VS2017 compiler.

10
  • 2
    That's what memove() is for. Commented Jun 12, 2017 at 1:13
  • 1
    »If the objects overlap the behavior is undefined.« en.cppreference.com/w/c/string/byte/memcpy Commented Jun 12, 2017 at 1:13
  • man memcpy : "The memory areas must not overlap." Commented Jun 12, 2017 at 1:13
  • thank you henri menke, u can post it as an answer so i can accept it Commented Jun 12, 2017 at 1:21
  • Use std::copy. Commented Jun 12, 2017 at 1:34

1 Answer 1

1

This is not ok: memcpy requires that the source and destination regions not overlap. C specifically provides the function memmove for cases where the regions do overlap.

Since you're tagged C++ here, you could also consider using std::copy as its constraint is weaker than memcpy: Just the the destination iterator must be outside the range to be copied, which is the case in your scenario.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.