Array bound checker

I’m tryin to using clang static analyzer tool for array bound checking but it seems fail , Here is an example :

#include

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 .

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