Search code examples
cmemcpy

Is it safe to use memcpy to shift elements in an array?


Let's say I have an integer array that contains junk and data. I wish to shift this array such that the data is at the start of the array.

Current:
[?, ?, ?, ?, 1, 1, 1, 1, 1]
 ----------  -------------
 JUNK        DATA

Desired:
[1, 1, 1, 1, 1, ?, ?, ?, ?]
 -------------  ----------
 DATA           JUNK

Is it safe to use memcpy to perform this shift?

memcpy(my_array, my_array + 4, 5)

I'm curious about the copy order of memcpy possibly corrupting the data shift.

Note: Before anyone asks, I'm working with legacy code. I think the true solution to my problem requires a circular buffer such that I don't have to shift data within an array.


Solution

  • You don't have to read far in the description of memcpy to find that you can't overlap source and destination.

    Here's the standard:

    7.21.2.1 The memcpy function

    Description

    2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined