How do I safely and sensibly determine whether a pointer points somewhere into a specified buffer?

后端 未结 2 511
广开言路
广开言路 2020-12-09 17:30

I\'m looking to implement a function that determines whether a given pointer points into a given buffer. The specification:


template          


        
2条回答
  •  旧时难觅i
    2020-12-09 18:34

    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 %.

提交回复
热议问题