Skip to main content
Sigvex

Array Deletion Index Remediation

Remove storage array elements with swap-and-pop so no zero-value gap is left behind for later iterations.

Array Deletion Index Remediation

Overview

Solidity’s delete array[i] zeroes an element but leaves array.length unchanged, creating a gap. Code that later iterates the array or counts entries by length will process the zero-value gap as real data. The fix is to remove the gap when deleting, most commonly by swapping the target with the last element and popping.

Related Detector: Array Deletion Index

Before (Vulnerable)

function remove(uint256 index) external {
    delete validators[index]; // Gap at index -- length unchanged
}

After (Fixed)

function remove(uint256 index) external {
    require(index < validators.length, "Out of bounds");
    validators[index] = validators[validators.length - 1];
    validators.pop(); // Length reduced, no gap
}

Swap-and-pop overwrites the removed slot with the last element and then shortens the array, so the length always equals the number of valid entries and no zero-value gap remains. Order is not preserved, which is acceptable for sets and registries.

Alternative Mitigations

  • When order matters, shift all later elements down by one, accepting the higher gas cost for small arrays.
  • Track membership in a mapping and use the array only for enumeration, removing from both consistently.
  • Maintain an explicit count of valid entries if gaps are unavoidable, and skip zero entries on read.

Common Mistakes

  • Using delete and assuming the array shrank.
  • Swapping with the last element but forgetting to call pop(), leaving a duplicate.
  • Reading array.length as the count of valid entries after gap-leaving deletions.

References