I wrote a small library of functions to do typical range checks as they
are needed in code that handles incoming packets or messages from
untrusted sources. My impetus was SMB code, in case you want to know.
Here is one of my functions:
static inline int range_ptrinbuf(const void* buf,unsigned long len,const void*
ptr) {
register const char* c=(const char*)buf; /* no pointer arithmetic on
void* */
return (c && c+len>c && (const char*)ptr-c<len);
}
Of course, when developing security critical code like this, you also
write a good test suite for it, that exercises all the cases. Here is
part of my test suite:
assert(range_ptrinbuf(buf,(unsigned long)-1,buf+1)==0);