In C and C++, is it undefined behavior to memcpy
into a const
variable when the number of bytes to be copied is zero?
int x = 0;
const int foo = 0;
memcpy( (void *)&foo, &x, 0 );
This question is not purely theoretical. I have a scenario in which memcpy
is called and if the destination pointer points to const
memory, then the size argument is guaranteed to be zero. So I'm wondering whether I need to handle it as a special case.
c c17
The older question Is it guaranteed to be safe to perform memcpy(0,0,0)? points out 7.1.4p1:
Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: 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.
The prototype for memcpy
is
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);
where the first parameter is not const
-qualified, and &foo
points to non-modifiable storage. So this code is UB unless the description of memcpy
explicitly states otherwise, which it does not. It merely says:
The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1.
This implies that memcpy
with a count of 0
does not copy any characters (which is also confirmed by 7.24.1p2 "copies zero characters", thanks Lundin), but it does not exempt you from the requirement to pass valid arguments.
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