17

I have the following code:

uint8_t buffer[16];
uint8_t data[16];
uint8_t buffer_length = 16;
uint8_t data_length = 0;

memcpy(buffer + buffer_length, data, data_length);

memcpy should be a no-op, because data_length is zero. However buffer + buffer_length points just outside of the allocated memory. I wonder if it could trigger some kind of undefined behaviour? Should I wrap this memcpy with an additional if?

I understand that any reasonable implementation of memcpy would work fine, however this question is more from the code correctness perspective and avoiding undefined behaviours.

13
  • 12
    You're allowed to create pointer to just after the end of an object. You're not allowed to dereference it. Since this doesn't dereference anything because the length is 0, I think it should be OK.
    – Barmar
    Sep 26 at 4:50
  • 4
    Using buffer + buffer_length doesn't violate the C standard, but is a loaded gun waiting to go off... Why would you want to form the address outside of the destination array in the first place?
    – Fe2O3
    Sep 26 at 4:57
  • 2
  • 2
    @12431234123412341234123 That question uses null pointers though, which are explicitly not valid pointers, per definition.
    – Lundin
    Sep 26 at 11:49
  • 3
    @Fe2O3: speculating, but given there's no point even calling memcpy if you know the length is 0, I'm going to guess "because actually sometimes the length is non-zero, but in those cases the destination will end up being buffer + buffer_length - data_length". The questioner just needs to know if they have to put in if (data_length) to avoid UB by the standard. Nothing else makes sense to me. Sep 27 at 0:19

3 Answers 3

22

As the answer of Stephen C points out, the C17 specification is a bit vague about whether or not this is well-defined.

However, the C23 specification clarifies this in a footnote to the part of 7.1.4 stating

If a function argument is described as being an array, the pointer 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 valid.

The footnote (235) reads:

This includes, for example, passing a valid pointer that points one-past-the-end of an array along with a size of 0, or using any valid pointer with a size of 0.

The first part of the sentence explicitly defines the OP case as well-defined.

Adding this statement can be seen as admitting that the C17 specification is not sufficiently clear on this point and thus, it cannot be ruled out that an implementer of a C17 compiler may in good faith interpret the standard such that this case is not defined behavior.

However, C23 should remove that uncertainty.

9
  • Thats footnote 235) in the C23 N3096 draft. And either way, foot notes are not normative. Although this one ought to point a knowledgeable reader straight to the actual normative text in 6.5.6 (C17/C23), as quoted in my answer.
    – Lundin
    Sep 26 at 8:03
  • 4
    @Lundin That is correct, but in this case, I see the footnote as a clarification of how the normative paragraph should be interpreted. It is not adding to the specification.
    – nielsen
    Sep 26 at 8:08
  • 2
    Yeah it's a good find - I don't think the clarification was necessary prior to C23 but apparently some people need one. It's generally muddy thinking to say that something in chapter 7 (the standard library) invalidates the rules laid out in chapter 6 (the C language). The standard library need not be implemented in the C language, but the function APIs definitely need to be and therefore (for the most part) the same rules apply to standard library functions as to any C function.
    – Lundin
    Sep 26 at 8:12
  • 1
    @Lundin: Such clarification shouldn't have been necessary, but there are many situations where the authors of the Standard didn't think it necessary to explicitly specify various aspects of behavior which implementations to date had either processed identically or in one of a few discrete ways (possibly chosen in unspecified fashion), but which clever compiler writers have interpreted such omissions as invitations to deviate in arbitrary fashion. The real problem, though, should be handled by recognizing adherence to precedent as a quality-of-implementation matter.
    – supercat
    Sep 26 at 15:47
  • 1
    @nigel222: If you allocate some whole number of aligned pages, and form begin and end=begin+length pointers, yes, end will point to the start of the next page. It's legal to have a pointer variable holding this pointer value, but it would be UB to do ++end. (On machines with flat memory models, pointer math is just unsigned integer math, but it's still UB in C, and some compilers for flat-memory-model machines may choose not to define the behaviour in such cases even though they trivially can.) As you say, it's UB to deref, but memcpy(end,end, 0) is required not to. Sep 27 at 14:20
9

The code has well-defined behavior.

The "string handling functions" that the memcpy function sorts under states (C17 7.24.1):

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.

The part in C17 7.1.4 regarding array parameters passed to standard library functions is somewhat relevant:

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.

(The arguments to memcpy need not necessarily be an array/arrays however. But in this case they both are.)

Address computations and the following access to an item of the array are defined by the rules for pointer arithmetic, specifically C17 6.5.6 §8 about the additive operators, the relevant part being this one:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

Therefore buffer + buffer_length is explicitly allowed by this "point one item past the end of an array" special rule, as long as we don't de-reference that location. Which will not happen in this case. Had we written buffer + buffer_length + 1 then it would be an invalid address computation and undefined behavior.

21
  • But doesn't 7.24.1 explicitely state, that the pointers passed have to be valid? If for example a particular implementation probes the destination pointer and discovers (by means of a hardware trap) that it is an invalid location, where would this be disallowed in the standard? The fact that buffer+buffer_length is a well-defined operation does not mean, that passing it to a function is well-defined.
    – Jens
    Sep 26 at 17:18
  • @Jens: I think you're conflating two things: a valid pointer, and a pointer that can be dereferenced. one-off-the-end of an array is a valid pointer for many purposes. The question then is whether this is one of them. Can memcpy legitimately probe the byte at address dest, which is outside the 0-length region of memory starting at dest that you've told memcpy to write to? The general thrust of the standard is "no, memcpy must not do that", and it's for the same reason it must not dereference dest+1 when you passed in dest and length 1. Sep 27 at 0:25
  • 1
    At least, not if it might trap. If an implementation wants to make special arrangements so that end-of-array always can be read for (at least) one byte, then its implementation of memcpy is welcome to do so under the "as if" rule. Sep 27 at 0:27
  • 1
    For that matter, if the implementation wants to deference dest+1024 on every call to memcpy, because it happens to know it's running on an architecture where it's safe to dereference literally any address: then that's permitted too. It conceivably on some non-stupid architecture even helps pre-populate cache lines to speed up big copies. But it's up to the implementation to make sure it's safe for that C implementation: it's not on you to pass it a pointer for which dest+1024 can be dereferenced per the standard. Sep 27 at 0:46
  • 1
    This is why it's always funny when authors of the Linux kernel have rows with authors of GCC over how the C standard should be interpreted. Often kernel code is running in contexts where either it wants some behaviour beyond the standard (such as the effect of dereferencing a null pointer, famously), and/or where the kernel code is part of the C implementation, not really C application code at all. Like, obviously the kernel memory allocator can't expect malloc to behave as specified, because it'll just recurse. But sometimes it's much less obvious. Such fun. Sep 27 at 0:52
-2

If the question is whether an conforming implementation could process such pointer constructs in gratuitously wacky fashion, the answer is almost certainly yes. If the question is whether programmers should be expected to jump through hoops to allow for such possibility, the answer is no. The Standard treats many such judgments as quality of implementation issues outside its jurisdiction.

In both clang and gcc, an equality comparison between a pointer to the start of an object, and a a legitimately formed "one past" pointer for the object that happens to immediately precede it in memory, may have side effects which are consistent neither with the comparison yielding 0, nor with it yielding 1. It would not, however, would probably not render such compilers non-conforming, because there would almost certainly exist some possible program which nominally exercises the translation limits in N1570 5.2.4.1, which clang and gcc would process correctly.

If there were an implementation that were incapable of correctly processing any program that exercises the translation limits in N5.2.4.1, other than one which passes a just-past pointer to memcpy with a size argument of zero, then one could argue that failure to treat that operation as a no-op might render the implementation non-conforming, or one could argue that because the Standard fails to unambiguously make clear that such behavior is required, the Standard would impose no requirements on a program that performs such an operation, but neither of those arguments would detract from the fact that quality implementations should be expected to treat the operation as a no-op, but the Standard would allow poor quality implementations to process such constructs in nonsensical fashion. Since the Standard deliberately waives jurisdiction over such quality-of-implementation issues, it should not be used as a source of guidance on such matters.

29
  • 3
    At risk of spoiling your fun, is answering every such question with, "C is a failed standard and means nothing. It has become a reverberating gong or a clashing cymbal" actually putting any pressure on the standard-writers, or implementers, or even C programmers? Any movement towards a document defining what a "quality implementation" of C is? ;-) Sep 27 at 0:33
  • 1
    That said, the comparison thing is rather significant for memmove, where you might reasonably expect the implementation to do some implementation-specific comparison of src and dest to decide how to copy. C++'s "potentially overlapping" concept provides implementations with a caveat along these lines, although I confess to having rather lost track of all this in recent years. Sep 27 at 0:41
  • @SteveJessop: Simple principle: if the simplest way of accomplishing a task with -O0 is simpler than any way that could be guaranteed to work at higher optimization settings, then for purposes of that task the so-called "optimizations" aren't. Otherwise, I think looking at compilers which aren't based on clang or gcc, and for which people are willing to pay money, should offer a clue.
    – supercat
    Sep 27 at 15:26
  • @SteveJessop: Both gcc and clang operate on an assumption that if two pointers compare equal, and a compiler would be entitled to assume that one of them wouldn't be used to access a particular object, it may apply that same assumption to both, despite the fact that the Standard explicitly recognizes situations where pointers would not be usable to access the same object and yet compare equal. Bug reports on such issues have been filed, but the compiler behavior is never changed. How should I interpret the seeming contradiction between clang/gcc behavior and the Standard?
    – supercat
    Sep 27 at 16:26
  • well, I haven't looked at those issues to form an opinion of my own, but I think it's fine to conclude that if clang/gcc do not behave as required by the standard, then neither is a conforming implementation. People do reach difference conclusions from the same text, so far as what is required by the standard. gcc in my experience doesn't make it easy enough even to disable individual optimisations that explicitly make it non-conforming, let alone disabling ones that the user thinks make it non-conforming but the author thinks conform. Sep 28 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.