Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions rules/g023_memory_array_allocation.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
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
}
}
17 changes: 17 additions & 0 deletions test/fixtures/g023_samples.sol
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Loading