Overview
Memory operations provide byte-addressable read/write access to the EVM’s transient linear memory. Memory is 256-bit word-aligned, zero-initialized, and expands dynamically with quadratic gas costs. 4 opcodes enable:- Load: MLOAD - Read 32-byte word
- Store: MSTORE - Write 32-byte word, MSTORE8 - Write single byte
- Copy: MCOPY - Copy memory regions (Cancun+, EIP-5656)
Opcodes
Memory Expansion
Memory is byte-addressable and expands in 32-byte words. When an operation accesses memory beyond the current size, expansion cost applies: Formula:- Access bytes 0-31 (1 word): 0 gas (no expansion)
- Access bytes 0-32 (2 words): 3 + 1 = 3 gas expansion
- Access bytes 0-256 (9 words): Quadratic scaling
Memory Model
- Size: Byte-addressable, up to 2^256 bytes theoretically (limited by gas)
- Initialization: All bytes zero-initialized
- Atomicity: 32-byte word operations are atomic
- Aliasing: No restriction - memory fully aliasable
- Scope: Ephemeral within transaction/call context
Overlap Handling
MCOPY handles overlapping source/destination regions correctly using temporary copy:Gas Costs
Memory operations charge base cost + memory expansion:| Operation | Base Gas | Memory Cost | Formula |
|---|---|---|---|
| MLOAD | 3 | Expansion | 3 + exp(offset+32) |
| MSTORE | 3 | Expansion | 3 + exp(offset+32) |
| MSTORE8 | 3 | Expansion | 3 + exp(offset+1) |
| MCOPY | 3 | Expansion + copy | 3 + exp(max(src+len, dest+len)) + ceil(len/32)*3 |
Common Patterns
Free Memory Pointer
Solidity maintains free memory pointer at 0x40:Dynamic Array Construction
Memory Copying
Implementation
TypeScript
Zig
Edge Cases
Zero-Length Operations
Large Memory Access
Byte Alignment
Memory Safety
Memory is isolated per transaction/call context:- No persistence: Memory cleared between calls
- No cross-contract visibility: Each call has independent memory
- No bounds check in application code: Out-of-memory accesses just allocate and charge gas
Hardfork Support
- MLOAD/MSTORE/MSTORE8: Frontier (genesis)
- MCOPY: Cancun (EIP-5656)
References
- Yellow Paper - Section 9.2 (Memory)
- EIP-5656 - MCOPY (Cancun)
- evm.codes - Interactive memory instruction reference
- Solidity Docs - Memory layout and assembly
Related Documentation
- Stack Operations - PUSH, DUP, SWAP
- Storage Operations - SLOAD, SSTORE
- Gas Constants - Gas cost definitions

