memcpy zero bytes into const variable – undefined behavior?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)