Skip to content
low Best Practice No SWC entry CWE-1176

Storage Variable Read Repeatedly in a Loop

SAFE-0260 Best Practice Checked automatically by the scanner
1

What goes wrong

A state variable or array length is read from storage on every loop iteration (SLOAD is expensive). Beyond gas cost, re-reading a length that a re-entrant call can change is also a subtle correctness risk.

2

The vulnerable pattern

proof of concept — how it is exploited
// for (uint i; i < items.length; ++i) total += balances[items[i]];
// items.length + each balances[...] SLOAD every iteration -> costly,
// and a callback that grows items mid-loop changes the bound.
3

How to fix it

the pattern that is safe
uint256 len = items.length;      // cache in memory
for (uint256 i; i < len; ++i) { ... }
Cache storage reads outside the loop.
4

Where this has happened

Largest recorded losses in the same failure class — related, not the same bug:

Check your own contract for this

The SaferICO scanner runs 201 detectors over your Solidity source, SAFE-0260 among them. Paste an address or the source itself — a small per-scan fee, shown before you sign, or unlimited on any plan.

Run the scanner See how it is attacked Read the docs