Is it legal to call memcpy with zero length on a pointer just past the end of an array?

前端 未结 3 643
渐次进展
渐次进展 2021-02-07 00:49

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条回答
  •  没有蜡笔的小新
    2021-02-07 01:06

    If we look at the C99 standard, there is this:

    7.21.1.p2

    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. ...

    There is no explicit statement in the description of memcpy in 7.21.2.1

    7.1.4.p1

    ... 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.

    Emphasis added. It seems the pointers have to point to valid locations (in the sense of dereferencing), and the paragraphs about pointer arithmetic allowing to point to the end + 1 do not apply here.

    There is the question if the arguments to memcpy are arrays or not. Of course they are not declared as arrays, but

    7.21.1.p1 says

    The header string.h declares one type and several functions, and defines one macro useful for manipulating arrays of character type and other objects treated as arrays of character type.

    and memcpy is in string.h.
    So I would assume memcpy does treat the arguments as arrays of characters. Because the macro mentioned is NULL, the "useful for..." part of the sentence clearly applies to the functions.

提交回复
热议问题