The code has well-defined behavior.
The "string handling functions" that the memcpy
function sorts under states (C17 7.24.1):
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. Unless explicitly stated otherwise in the description of a
particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4.
The part in C17 7.1.4 regarding array parameters passed to standard library functions is somewhat relevant:
If a function argument is described as being an array, the pointer actually passed
to the function shall have a value such that all address computations and accesses to objects (that
would be valid if the pointer did point to the first element of such an array) are in fact valid.
(The arguments to memcpy
need not necessarily be an array/arrays however. But in this case they both are.)
Address computations and the following access to an item of the array are defined by the rules for pointer arithmetic, specifically C17 6.5.6 §8 about the additive operators, the relevant part being this one:
If both the pointer operand and the result point
to elements of the same array object, or one past the last element of the array object, the evaluation
shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past
the last element of the array object, it shall not be used as the operand of a unary * operator that is
evaluated.
Therefore buffer + buffer_length
is explicitly allowed by this "point one item past the end of an array" special rule, as long as we don't de-reference that location. Which will not happen in this case. Had we written buffer + buffer_length + 1
then it would be an invalid address computation and undefined behavior.
buffer + buffer_length
doesn't violate the C standard, but is a loaded gun waiting to go off... Why would you want to form the address outside of the destination array in the first place?memcpy
if you know the length is 0, I'm going to guess "because actually sometimes the length is non-zero, but in those cases the destination will end up beingbuffer + buffer_length - data_length
". The questioner just needs to know if they have to put inif (data_length)
to avoid UB by the standard. Nothing else makes sense to me.