2

Is there a problem in passing 0 to memcpy():

 memcpy(dest, src, 0)

Note that in my code I am using a variable instead of 0, which can sometimes evaluate to 0.

gsamaras
  • 71,951
  • 46
  • 188
  • 305

2 Answers2

8

As one might expect from a sane interface, zero is a valid size, and results in nothing happening. It's specifically allowed by the specification of the various string handling functions (including memcpy) in C99 7.21.1/2:

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. [...] On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

Yes, it's totally Ok. The only restriction on memcpy is that memory areas must not overlap.

ivaigult
  • 6,198
  • 5
  • 38
  • 66
  • 3
    That's not true, there is also a restriction that `dest` and `src` are valid pointers, meaning they cannot be null. See 7.23.1 and 7.1.4 – Jonathan Wakely May 28 '15 at 12:51
  • 3
    That's not the only restriction (both pointers must be valid, and `dest` must be at least as large as `n`, for example). But you're right that there's no restriction that `n` be non-zero. – Mike Seymour May 28 '15 at 12:52