Member-only story
Solidity Tutorial: All About Memory
Understanding the short term memory of the EVM
This is Part II of the “All About Data Locations” sub-series.
We will learn the layout of the EVM memory, its reserved spaces, the free memory pointer, how to use memory
references to read and write from/to memory and the conventional best practices when working with memory.
We will use code snippets of the contracts from the Ethereum Name Service (ENS) to support this article with meaningful examples. This will help us understand better how the smart contracts behind this popular project work under the hood.
Table of Content
- Introduction
- The EVM Memory — Overview
- Layout of Memory
- Basics of Memory
- Reading from Memory (
MLOAD
) - Writing to Memory (
MSTORE
+MSTORE8
) - Knowing the Memory Size (
MSIZE
) - The Free memory pointer
memory
references as functions parametersmemory
references inside functions body- The Memory Expansion cost
- Memory between contract calls
- Conclusion
Introduction
In the introductory article “All About Data Locations”, I describe the EVM as an industrial factory. In some parts of a factory, you will find machines and robots controlled by operators.
These machines break down large pieces of steel/aluminium that cannot be processed (e.g., fit through the furnace door) into smaller chunks.
We can use the same example for Ethereum. The EVM operates as a stack machine on 32 bytes words. When the EVM encounters data larger than 32 bytes (complex types like string
, bytes
, struct
or arrays), it cannot process them on the stack because these items are too large.
Therefore, the EVM needs to take this data and process it elsewhere. It has a dedicated place for this: the memory. By putting such variables in memory, the EVM can then deliver them to the stack in smaller chunks, one after the other.