diff --git a/rules/g023_memory_array_allocation.rs b/rules/g023_memory_array_allocation.rs new file mode 100644 index 0000000..9cd1ee1 --- /dev/null +++ b/rules/g023_memory_array_allocation.rs @@ -0,0 +1,36 @@ +//! Rule G023: Flag Unused Capacity Allocations in Memory Arrays. +//! +//! Detects memory array declarations initialized with large fixed sizes +//! that are only partially populated during execution, which wastes gas +//! on unnecessary memory expansion. + +pub struct RuleG023MemoryArrayAllocation; + +impl RuleG023MemoryArrayAllocation { + pub fn name() -> &'static str { + "G023_memory_array_allocation" + } + + pub fn check(source_code: &str) -> Vec { + let mut warnings = Vec::new(); + + for line in source_code.lines() { + let trimmed = line.trim(); + if !trimmed.starts_with("//") && trimmed.contains("new uint") && trimmed.contains("[]") + { + let has_loop = source_code.contains("for (") + || source_code.contains("while (") + || source_code.contains("do {"); + if !has_loop { + warnings.push( + "Warning: Memory array allocated with size without corresponding \ + population loop; consider resizing to match actual usage" + .to_string(), + ); + } + } + } + + warnings + } +} diff --git a/test/fixtures/g023_samples.sol b/test/fixtures/g023_samples.sol new file mode 100644 index 0000000..990c34b --- /dev/null +++ b/test/fixtures/g023_samples.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract G023Samples { + function oversized() external pure { + uint256[] memory arr = new uint256[](100); + arr[0] = 1; + } + + function appropriate() external pure { + uint256 size = 10; + uint256[] memory arr = new uint256[](size); + for (uint256 i = 0; i < size; i++) { + arr[i] = i; + } + } +}