Memory struct provides a dynamically expanding heap for EVM memory operations. It automatically extends when data is stored beyond the current size.
Structure
Methods
new()
Creates a new empty memory instance.Returns a new memory instance with an empty heap
mstore()
Stores 32 bytes of data at the specified memory location. Note: This method is marked asunsafe because it uses raw pointer operations.
The memory location to store the data
The 32-byte value to store
mload()
Loads 32 bytes of data from the specified memory location. Note: This method is marked asunsafe because it uses raw pointer operations.
The memory location to load from
Returns the 32-byte value at the specified location
msize()
Returns the current size of the memory heap in bytes.The current heap size in bytes
Usage Examples
Aligned Memory Storage
Storing data at memory locations that are multiples of 32:Unaligned Memory Storage
The memory automatically extends to accommodate unaligned locations:Read-Only Memory Access
Theload_only() method provides read access without automatic extension:
Memory Expansion
The memory heap automatically expands when:- Storing data beyond the current heap size
- Loading data beyond the current heap size
- If
location % 32 == 0: Extends by exactly(location + 32) - heap.len() - Otherwise: Extends by
(location + 32 + (location % 32)) - heap.len()
Safety Considerations
All memory operations (mstore, mload, load_only) are marked as unsafe because they:
- Use raw pointer arithmetic
- Directly manipulate memory via pointers
- Assume 32-byte alignment for data
- The heap has been properly extended
- Location values are valid
- No concurrent access to the same memory location