Unchecked Array Bounds Remediation
Overview
Related Detector: Unchecked Array Bounds
Solidity 0.8+ reverts on out-of-bounds storage array access, but assembly and some memory operations do not, and relying on revert-based protection can itself be a denial of service. When an index comes from calldata or external data, validate it before use. The remediation is an explicit bounds check that fails cleanly.
Recommended Fix
Before (Vulnerable)
function itemAt(uint256 i) external view returns (bytes32 v) {
// Assembly access performs no bounds check; a large i reads arbitrary memory.
bytes32[] memory data = _data;
assembly { v := mload(add(add(data, 0x20), mul(i, 0x20))) }
}
After (Fixed — explicit bounds check)
error IndexOutOfBounds();
function itemAt(uint256 i) external view returns (bytes32) {
bytes32[] memory data = _data;
if (i >= data.length) revert IndexOutOfBounds();
return data[i];
}
Prefer high-level indexed access (which is checked) over assembly. Where assembly is unavoidable, compute and enforce the bound explicitly before the mload/calldataload.
Common Mistakes
- Assuming 0.8’s automatic checks cover memory arrays and assembly — they do not.
- Using a revert as the only guard on a hot path, letting an attacker grief callers by forcing reverts.
- Validating the index but not the length of an externally supplied array before iterating it.