C# static array bound check

365 views Asked by At

Is there a tool for C# which can statically (without executing the code) detect out of bound array access, i.e., array access that will throw IndexOutOfRangeException.

Thank you.

EDIT: Yes, I am aware that it is a theoretically impossible to do it in general case (i.e., it is undecidable), but that that does not mean that it is not possible to do it for some cases (in fact the whole field of formal verification is about producing practical tools for theoretically impossible things). (I didn't think this commend was specially required :))

3

There are 3 answers

1
Robin Green On BEST ANSWER
3
Thomas Weller On

No, it's theoretically just not possible. This is what unit tests are made for ;-).

1
Luaan On

As Thomas and Heinzi have said, this is undecidable. There is a subset of your problem that is solvable - you could NGen (or JIT) your .NET application, and look for references to the IndexOutOfRangeException throw subroutine; the MSIL -> native compiler eliminates bounds checks (and thus IndexOutOfRangeExceptions) if it's absolutely certain that it simply can't occur.

In practice, that's usually code like for (int i = 0; i < ar.Length; i++) { ar[i] ... }, but it should trim down the undetermined cases considerably in many applications.