I\'m looking to implement a function that determines whether a given pointer points into a given buffer. The specification:
template
If you cast the pointers to large enough unsigned integers and add number of bytes instead of number of objects, the undefined behavior goes away.
template
bool points_into_buffer (T *p, T *buf, std::size_t len) {
uintptr_t ip = (uintptr_t)p;
uintptr_t ibuf = (uintptr_t)buf;
return ip >= ibuf && ip < (ibuf + sizeof(T) * len);
}
This code doesn't detect if p is not correctly aligned, but you could easily add a test with a %.