title: Is it legal to call memchr with a too-long length, if you know the character will be found before reaching the end of the valid region?
body: <p>Is the following defined behavior in C11 and C++11<sup>1</sup>?</p>
  
  <pre><code>bool has4() {  
      char buf[10] = {0, 1, 2, 4};
      return memchr(buf, 4, 20);
  }
  </code></pre>
  
  <p>Here we pass a too-long length to <code>memchr</code>. The array has 10 elements but we pass 20. The element we are searching for, however, is always found before the end. It is clear to me if this is legal.</p>
  
  <p>If this is allowed, it would limit implementation flexibility, since the implementation cannot rely on the size being a valid indication of the size of the accessible memory region and hence must be careful about reading beyond the found element. An example would be an implementation that wants to do a 16 byte SIMD load starting at the passed-in pointer and then check all the 16 bytes in parallel. If the user passes a length of 16, this would be safe only if the entire length was required to be accessible.</p>
  
  <p>Otherwise (if the above code is legal) the implementation must avoid potentially faulting on elements past the target element, for example by aligning the load (potentially expensive) or checking if the pointer is near the <a href="https://stackoverflow.com/q/37800739/149138">end of a protection boundary</a>.</p>
  
  <hr>
  
  <p><sup>1</sup> Here's one of those rare questions where I guess tagging both C and C++ is valid: as far as I can tell the C++ standard just defers directly to the C standard here, via reference, in terms of behavior, but if that's not the case I want to know.</p>