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 gas

    • using a hash function to mstore like storage does is not recommended

  • mstore(p, v) - stores value v in slot p (just like sload )

  • mload(p) retrieves 32 bytes from slot p [p….0x20]

  • mstore8(p, v) works similar to mstore but only for one byte

  • msize() returns the largest accessed memory index in the transaction

Example

  • mstore(0x00, x) → stores x in the first 8 bytes

  • mstore(0x01, y) → stores y second 8 bytes (instead of moving forward 32 bytes in storage)

function mstore8() external pure {
        assembly {
            mstore8(0x00, 7) // write to the first byte in memory 0x07 
            mstore(0x00, 7) // overrides the initial store, 0x00..007 (32 bytes) 
        }
    }

How Solidity uses Memory

  • 0x00 - 0x3f (64 bytes): scratch space for hashing methods

  • 0x40 - 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 slot

  • memory starts being stored in slot 0x80

  • abi.encode and abi.encodePacked - stored in memory

  • Structs 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