I am not so well-versed in the C standard, so please bear with me.
I would like to know if it is guaranteed, by the standard, that memcpy(0,0,0)
is safe.
The only restriction I could find is that if the memory regions overlap, then the behavior is undefined...
But can we consider that the memory regions overlap here ?
The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.
memmove() is similar to memcpy() as it also copies data from a source to destination.
memcpy is usually naive - certainly not the slowest way to copy memory around, but usually quite easy to beat with some loop unrolling, and you can go even further with assembler.
memcpy can happen with _first_group as a null pointer and count 0 . Passing null to the second argument is an undefined behavior, even if count is zero.
I have a draft version of the C standard (ISO/IEC 9899:1999), and it has some fun things to say about that call. For starters, it mentions (§7.21.1/2) in regards to memcpy
that
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. 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.
The reference indicated here points to this:
If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.
So it looks like according to the C spec, calling
memcpy(0, 0, 0)
results in undefined behavior, because null pointers are considered "invalid values."
That said, I would be utterly astonished if any actual implementation of memcpy
broke if you did this, since most of the intuitive implementations I can think of would do nothing at all if you said to copy zero bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With