Violet Giraffe
Violet Giraffe

Reputation: 33607

Is it allowed for src and dest arguments of memcpy to overlap?

I need to shift contents of a byte buffer. Naturally, I started writing memcpy, but then realized it might have restrict specifier for the source and dest. My implementation (MSVC 2013) doesn't seem to have it. Cppreference lists two memcpy versions, with and without restrict, but I don't get it - I don't think these are overloads, and it's unclear to me how the compiler could correctly determine which one to pick. On the other hand, the memcpy function could analyze the addresses and the count argument at runtime to determine if the address ranges overlap or not.

So, is it allowed to call memcpy with overlapping arguments? If not, is there any way to perform this operation that is better than plain for?

Upvotes: 0

Views: 824

Answers (2)

Dan Byström
Dan Byström

Reputation: 9244

The memory in memcpy cannot overlap or you risk undefined behaviour.

Use memmove instead.

Upvotes: 1

Holt
Holt

Reputation: 37641

No it is not, you should use memmove.

From memcpy(3):

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap.

From memmove(3):

The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest.

The restrict keyword was added in the C99 standard, it is why cppreference lists both versions (if you look carefully on the right, you can see until C99 and since C99).

Upvotes: 6

Related Questions