<<< Date Index >>>     <<< Thread Index >>>

Re: gcc 4.1 bug miscompiles pointer range checks, may place you at risk



On Mon, 17 Apr 2006, Felix von Leitner wrote:
> 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);
> }
>
> [...]
>
>   assert(range_ptrinbuf(buf,(unsigned long)-1,buf+1)==0);
>
> Imagine my surprise when this assertion failed. [...] "c+len>c" is
> the code with which you would typically check for integer overflows,

Most commonly integer overflows happens with integers (not pointers).
Try to convert pointers to unsigned (this should work, although it is
not portable).

According to the C standard the semantic of pointers is different from
the semantic of integers, so TTBOMK gcc is doing the right thing.

<http://www-ccs.ucsd.edu/c/express.html>:

 You can add an integer to a value of type pointer to object. If the
 value of the pointer is the address of an array element, then adding
 one to the value yields the address of the next array element. [...]
 If you form any other address that does not designate an element of
 the array object (by adding an integer to a pointer), the result is
 undefined.

 You can compare two pointer values only if they are the addresses of
 elements within (or just beyond) the same array object.

-- 
Regards,
ASK