Collection Size Or Array Length¶
What does this mean ?¶
For standard arrays and collections, length/count cannot be negative. A condition such as Count >= 0 therefore does not establish that an element exists. This rule detects a likely logic error, not automatically a security vulnerability.
What can happen ?¶
Code may enter a branch intended for nonempty input and then fail when accessing the first element. The impact depends on what that branch does; a count comparison alone does not demonstrate unauthorized access.
Recommendation¶
Use the condition that matches the intended requirement. Prefer a collection's count/empty property where available. For an arbitrary C# IEnumerable<T>, Any() checks whether an element exists without requesting a full count, but enumeration can have side effects. Handle null and concurrent changes according to the caller's contract.
Sample Code¶
// Incorrect when the intention is “contains an element”.
bool hasItems = items.Count >= 0;
// Correct for a non-null List<T>.
bool hasItemsCorrected = items.Count > 0;
// Java List, assumed non-null
boolean hasItems = !items.isEmpty();
// JavaScript/TypeScript array, validated by the caller
const hasItems = items.length > 0;
A nonempty check does not prove that an arbitrary index is valid. Check 0 <= index && index < length for the index actually used.
Regression checks¶
Exercise an empty collection, one element and an invalid index. Include null only if the API contract permits it. For shared mutable collections, test the actual synchronization strategy rather than assuming a count check makes a later access atomic.