Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated examples

...

Code Block
bgColor#ffcccc
langcpp
void f(const char *buf;
, size_t len) ={
 1 << 30;

/* // Check for overflow
  */
if (buf + len < buf) {
    len = -(size_t)buf - 1;
  }
}

This code resembles the test for wraparound from the sprint() function as implemented for the Plan 9 operating system. If buf + len < buf evaluates to true, len is assigned the remaining space, minus one byte. However, because the expression buf + len < buf constitutes undefined behavior, compilers can assume this condition will never occur and optimize away the entire conditional statement.

...

Code Block
bgColor#ccccff
langcpp
#include <cstdint>
 
void f(const char *buf;
, size_t len) ={
 1 << 30;

/* // Check for overflow */
if (
  auto bint = reinterpret_cast<std::uintptr_t>(buf);
  if (bint + len < reinterpret_cast<std::uintptr_t>(buf))bint) {
    len = -(size_t)bufbint - 1;
  }
}

This compliant solution works on architectures that provide a linear address space. Some word-oriented machines are likely to produce a word address with the high-order bits used as a byte selector, in which case this solution will fail. Consequently, this is not a portable solution.

...