As answered elsewhere, calling functions like memcpy
with invalid or NULL
pointers is undefined behaviour, even if the length argument is zero. In the
3.15 object
- object region of data storage in the execution environment, the contents of which can represent values
The memory, pointer to one past the last element points to, of an array object or an object cannot represent values, since it cannot be dereferenced ( 6.5.6 Additive operators, paragraph 8 ).
7.24.2.1 The memcpy function
- The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
Pointers passed to memcpy must point to an object.
6.5.3.4 The sizeof and _Alignof operators
- When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array. When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.
sizeof operator doesn't count the one-past element as the object, since it doesn't count towards the size of the object. Yet it clearly gives the size of the entire object.
6.3.2.1 Lvalues, arrays, and function designators
- An lvalue is an expression (with an object type other than void) that potentially designates an object; 64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined.
I argue that the one past pointer to an array object or an object, both of which are otherwise allowed to point to, does not represent an object.
int a ;
int* p = a+1 ;
p
is defined, but it does not point to an object since it cannot be dereferenced, the memory it points to cannot represent a value, and sizeof doesn't count that memory as a part of the object. Memcpy requires a pointer to an object.
Therefore the passing one past pointer to memcpy causes undefined behavior.
Update:
This part also support the conclusion:
6.5.9 Equality operators
- Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
This implies that pointer to an object if incremented to one past an object, can point to a different object. In that case, it certainly cannot point to the object it pointed to originally, showing that pointer one past an object doesn't point to an object.