Rules › Anchor (Rust)

init_if_needed (reinitialization risk)

mediumAnchor (Rust)Rule anchor-init-if-needed

init_if_needed accepts accounts that already exist; without checks an attacker can reset or reuse state.

Why it matters

init_if_needed creates the account if it doesn't exist and otherwise accepts the existing one. That makes it easy to write an instruction that can be called again to reset state, or that accepts an account initialized by someone else with different parameters. Anchor gates it behind a feature flag for this reason. Prefer a separate init instruction, or check the account's state explicitly.

Vulnerable

#[account(init_if_needed, payer = user, space = 8 + Vault::INIT_SPACE)]
pub vault: Account<'info, Vault>,

Fixed

#[account(init, payer = user, space = 8 + Vault::INIT_SPACE, seeds = [b"vault", user.key().as_ref()], bump)]
pub vault: Account<'info, Vault>,

What other tools call it

ToolDetector or reference
Anchorrequires the init-if-needed feature
Sealevel attacks4-initialization

Check your code

Paste a contract into the in-browser checker, or let the Claude Code plugin scan before every deploy. The quick check for this rule is a pattern match: treat a hit as "look here", and a miss as no guarantee.

Static analysis finds known bug classes; it can't prove code is safe and isn't an audit. Get a professional audit before deploying code that will hold value.