Demystifying Memory in EVM (Part I)

Demystifying Memory in EVM (Part I)

Let’s look at the architecture of the Memory in EVM.

Scratch Space : Ephemeral space to write values ( used for instance by the sha3 opcode)

Free Memory Pointer : It contains the address of the last byte accessed in memory . Memory never gets cleaned , which means that free memory pointer only increases and never decreases. When a contract gets executed , the free memory pointer first value is always “ 0×80 “

Memory Structure

  • Slot Space : memory in the EVM has a theoretically large address space of

    2^ 256 slots

  • Byte-Addressable : Each slot in the memory can hold one byte of data . This means you can address each individual byte , unlike storage where slots hold 32 bytes

Word Size

  • Despite being byte-addressable , EVM memory operation typically works with 32-byte(256-bit) words. This means that many memory operation read or write 32 bytes at a time.

Practical Implementation

  • Individual Bytes : You can read or write individual bytes in memory for example , if you allocate an array of bytes , each element occupies exactly one byte.

  • 32byte Chunk : When dealing with data structures like integers addresses or fixed-size arrays , the EVM often handles these as 32-byte words.

    For instance ,a uint 256 variable occupies a full 32-byte slot in memory

Let’s look at a basic code to understand the mstore keyword

contract MemoryExample{
    function storeAtMemory() public pure {
        uint256 value=1;
        assembly{
            // store the value 1 at memory loction 0x00
            mstore(0x00,value)
        }
    }
}
  • The mstore keyword uses exactly 32-bytes to store any data variable

As you can see “1” will be stored on the 20th byte occupying the whole slot