Is memcpy(&a + 1, &b + 1, 0) defined in C11?

后端 未结 2 1607
生来不讨喜
生来不讨喜 2020-12-17 08:00

This question follows this previous question about the definedness of memcpy(0, 0, 0), which has been conclusively determined to be undefined behavior.

相关标签:
2条回答
  • 2020-12-17 08:38

    While the "correct" answer according to the standard appears to disagree, I can find it only disingenuous that after int a[6]; int b[6]; all of

    memcpy(a+0, b+0, 6);
    memcpy(a+1, b+1, 5);
    memcpy(a+2, b+2, 4);
    memcpy(a+3, b+3, 3);
    memcpy(a+4, b+4, 2);
    memcpy(a+5, b+5, 1);
    

    should be valid (and copy an area ending at the end of the arrays) while

    memcpy(a+6, b+6, 0);
    

    is valid in light of the count but not of the addresses. It's the same end of the copied area!

    Personally, I'd lean towards defining memcpy(0,0,0) being valid as well (with the rationale of just demanding valid pointers but no objects) but at least it's a singular case while the "end of array" case is an actual exception to an otherwise regular pattern for copying an area at the end of an array.

    0 讨论(0)
  • 2020-12-17 08:45

    C11 says:

    (C11, 7.24.2.1p2) "The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1."

    &a + 1 itself is a valid pointer to integer addition but &a + 1 is not a pointer to an object, so the call invokes undefined behavior.

    0 讨论(0)
提交回复
热议问题