[cfe-dev] Array bound checker

Carlos Galvez via cfe-dev cfe-dev at lists.llvm.org
Tue Jan 25 06:17:25 PST 2022


Hi,

Since the indexing is only known at runtime, out-of-bounds may or may not
happen, and it's not possible to detect this statically. Therefore you need
to resort to runtime checks, like UB sanitizer, to detect if indeed that's
the case.

What is possible to detect statically is doing indexing operations using
variables (not compile-time constants) as indices. You can use clang-tidy's
cppcoreguidelines-pro-bounds-constant-array-index to get warnings about
code that performs indexing without compile-time constants:

https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-bounds-constant-array-index.html

Example:
https://godbolt.org/z/4McYx8vKs


On Tue, Jan 25, 2022 at 9:48 AM phy coder via cfe-dev <
cfe-dev at lists.llvm.org> wrote:

> I'm tryin to using clang static analyzer tool for array bound checking but
> it seems fail , Here is an example :
>
> #include <iostream>
>
> int main() {
> int size;
> std::cin >> size;
>
> int array[size];
>
> for(int i = 0 ; i < n ; i++){
> std::cin>>array[i] ;
> }
>
> int test[20] = {9,6,8,9,0,4,5,,3,2,7,8,9,8,12,34,87,43,65,32,23} ; // Just
> for testing
> for(int i = 0 ; i < size; i++){
> std::cout << test[array[i]] << " " ;
> }
>
> return 0;
> }
>
> There is a bug in this program that we are using the value of "array" as
> an index for the "test array"  , the value of "array" depends on the user
> and it's very obvious that the user might enter the negative value . When I
> used the clang static analyzer (--analyze) , it's not able to catch this
> and I didn't find any CSA checker for array bounds bug on the site . I also
> tried using the undefined behavior array bound checker for it , it's
> working when the user enters any negative value otherwise it was quite af .
> To be honest I didn't expect that this bug would be caught by UBsanitizer .
> But I was expecting this with clang static analyzer which seems to fail .
>
> Sorry , If any tool exists for this which I wasn't aware of .  Le'me know
> if there is any tool that exists for this .
>
> Thank you .
> _______________________________________________
> 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/20220125/6cbb28c1/attachment.html>


More information about the cfe-dev mailing list