[cfe-dev] Negative Index of Pointer

Jessica Clarke via cfe-dev cfe-dev at lists.llvm.org
Thu Jan 27 04:55:36 PST 2022


If you’re talking about UBSan’s out of bounds detection, this is a known gap, it only handles the most trivial cases where you’re directly indexing an array with a known size. Round-tripping through a temporary pointer variable as in your case is enough to obfuscate it so it doesn’t know the array’s bounds and will only detect pointer overflow (as in, wrapping the address space). Whilst you could relatively easily teach UBSan to be able to peek through such cases, in the general case detecting out of bounds indices requires a whole new ABI that modifies pointers such that they carry the bounds of their underlying object (whatever your interpretation of C has that mean).

Jess

> On 27 Jan 2022, at 09:16, phy coder via cfe-dev <cfe-dev at lists.llvm.org> wrote:
> 
> So, I was trying to do this  , what I was expecting is undefined behavior by ptr[-4] and b[-4] but the undefined behavior is only shown by b[-4] . I know that a pointer can have a negative index when there is some defined value at that address . But in this case , sanitizer has to give undefined behavior for ptr[-4]  but there is no such error . I'm not sure if this is considered as Undefined Behavior or not . Or maybe some other tools exist for this type of undefined behavior .
> 
> 
> #include <iostream>
> 
> int main() {
>   
>     int b[]= {7,5,4,3,2} ;
> 
>     char a[] = "hello";
>     char *ptr = a;
>     std::cout<< ptr[0] << ptr[-4] << b[0] << b[-4];
> }
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20220127/69660e02/attachment.html>


More information about the cfe-dev mailing list