Memory
Features of memory
Uses of memory in Solidity
Get and return values to external calls
Set the function arguments for external calls
Revert with an error string
Log messages
Create other smart contracts
Using
keccak256
Memory in Solidity is equivalent to the heap in other languages
No garbage collector or
free
Solidity memory is laid out in 32 byte sequences (like storage)
Accessed using [0x00 - 0x20], [0x20 - 0x40], [0x40 - 0x60], [0x60 - 0x80] ā¦ā¦.
Only four instructions that affect memory:
mload
,mstore
,mstore8
,msize
In pure Yul programs, memory is easy to use, but in mixed Solidity/Yul programs, Solidity expects memory to be used in a specific way
Overview
Gas is charged for each memory access, and how far into the memory array you accessed
E.g.
mload(0xffffffffffffffff)
will run out of gasusing a hash function to
mstore
like storage does is not recommended
mstore(p, v)
- stores value v in slot p (just likesload
)mload(p)
retrieves 32 bytes from slot p [pā¦.0x20]mstore8(p, v)
works similar tomstore
but only for one bytemsize()
returns the largest accessed memory index in the transaction
Example
mstore(0x00, x)
ā stores x in the first 8 bytesmstore(0x01, y)
ā stores y second 8 bytes (instead of moving forward 32 bytes in storage)
How Solidity uses Memory
0x00
-0x3f
(64 bytes): scratch space for hashing methods0x40
-0x5f
(32 bytes): currently allocated memory size (aka. free memory pointer, points to the end of the last allocated block)0x60
-0x7f
(32 bytes): empty slotmemory starts being stored in slot 0x80
abi.encode
andabi.encodePacked
- stored in memoryStructs and arrays (by explicitly using the
memory
keyword)Function arguments
objects in memory are laid out end to end, arrays have no
push
unlike storage
Last updated