-1

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.

Izzo
  • 4,461
  • 13
  • 45
  • 82
  • See https://stackoverflow.com/questions/4415910/memcpy-vs-memmove and https://riptutorial.com/c/example/2150/copying-overlapping-memory – jarmod Mar 07 '21 at 16:57

1 Answers1

3

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

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118