Skip to main content
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.

Overview

Opcode: 0x52 Introduced: Frontier (EVM genesis) MSTORE writes a 32-byte word to memory at the specified offset. The value is taken from the stack as a 256-bit unsigned integer and written in big-endian order. This is the primary mechanism for writing arbitrary data to memory during execution.

Specification

Stack Input:
Stack Output:
Gas Cost: 3 + memory expansion cost Operation:

Behavior

MSTORE pops two values: offset (top of stack) and value (next). It writes the 32-byte representation of value to memory starting at offset.
  • Offset is interpreted as unsigned 256-bit integer
  • Value is written as 32 bytes in big-endian order (most significant byte first)
  • Memory automatically expands to accommodate write (quadratic cost)
  • Overwrites existing memory without checking
  • All 32 bytes are always written (no partial writes)

Examples

Basic Store

Write All Ones

Write Zero (Clear Memory)

Write at Non-Aligned Offset

Sequential Writes

Gas Cost

Base cost: 3 gas (GasFastestStep) Memory expansion: Quadratic based on access range Formula:
Examples:
  • Writing bytes 0-31: 1 word, no prior expansion: 3 gas
  • Writing bytes 1-32: 2 words (rounds up), 1 word prior: 3 + (4 - 1) = 6 gas
  • Writing bytes 0-4095: ~125 words: 3 + (125² / 512 + expansion) ≈ 3 + 30 = 33 gas
Memory cost dominates for large writes.

Edge Cases

Overwriting Memory

Partial Overlap

Out of Gas

Stack Underflow

Common Usage

Update Free Memory Pointer

Encode Function Return

Build ABI-Encoded Calldata

Temporary Storage (Local Variables)

Memory Safety

Write safety properties:
  • No side effects: Writing memory doesn’t affect storage or state
  • Atomic writes: 32-byte write is atomic
  • Initialization: Uninitialized memory automatically allocated
  • Overwrite safety: Always replaces all 32 bytes
Applications must ensure offset correctness:

Implementation

Testing

Test Coverage

Edge Cases Tested

  • Basic write (32 bytes)
  • Zero write (memory clear)
  • Non-aligned offset
  • Overwrite handling
  • Word boundary alignment
  • Stack underflow/overflow
  • Out of gas conditions
  • Big-endian encoding

Security Considerations

Incorrect Free Pointer Management

Memory Overlap Bugs

Benchmarks

MSTORE is among the fastest EVM operations: Relative performance:
  • MSTORE (new memory): 1.0x baseline
  • MSTORE (existing memory): 1.0x baseline
  • MLOAD: 1.0x (similar cost)
  • SSTORE: 100x slower (storage vs memory)
Gas scaling:
  • First word: 3 gas
  • Second word: 3 gas (small expansion)
  • Large memory: Quadratic scaling beyond practical use

References