1

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 :))

Ivan
  • 85
  • 1
  • 7

3 Answers3

2

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

Thomas Weller
  • 11,631
  • 3
  • 26
  • 34
  • 1
    Just theoretically? It's not possible, period. – GregRos Dec 06 '13 at 16:51
  • If theory already says 'This is not possible', then in fact it is two times impossible in practice. Period ;-). – Thomas Weller Dec 06 '13 at 16:55
  • 1
    The theory does not say: "This is not possible", but rather: "There is no method which can find all such bugs in every program". In practice, many model checker (mostly for C) can do that. – Ivan Dec 06 '13 at 17:18
2

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.

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • 2
    In case anyone is curious, here is some info about bounds checking elimination in the CLR (non technical): http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx – GregRos Dec 06 '13 at 16:53
1

Yes, Code Contracts for .NET. See this article in MSDN magazine.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • 1
    Thank you. This seems like the answer I was looking for: "**Static Checking**. Our static checker can decide if there are any contract violations without even running the program! It checks for implicit contracts, such as null dereferences and array bounds, as well as the explicit contracts." – Ivan Dec 09 '13 at 11:45