Skip to content
Critiq Docs

Search docs

Search documentation pages and rules

correctness.resource-leak

Avoid defer inside loops

defer inside a loop holds resources until the surrounding function returns.

#Metadata

Rule ID
go.correctness.defer-in-loop
Severity
medium
Confidence
0.85
Languages
go
Presets
strict
Stability
stable
Applies to
block
Tags
correctness, go, resource-leak, rules-catalog

#Why it matters

`defer` runs when the enclosing function returns, not when the iteration ends. Deferring inside a `for` or `for ... range` block accumulates open handles for the lifetime of the function and can exhaust file descriptors or memory.

#Remediation

Wrap the per-iteration work in a helper or closure so the deferred call runs when the iteration ends, not at function return.

#Repository path

The generated metadata points to critiq-rules/libs/rules/catalog/rules/go/go.correctness.defer-in-loop.rule.yaml.