# `EEVM.Gas.Memory`
[🔗](https://github.com/mw2000/eevm/blob/main/lib/eevm/gas/memory.ex#L1)

Memory expansion gas cost calculation.

EVM memory is a byte-addressable array that starts empty and expands on demand.
Expanding memory is not free — the cost grows quadratically to discourage excessive
memory usage.

## Formula (Yellow Paper, Appendix H)

    cost(words) = 3 × words + words² ÷ 512

where `words = ceil(byte_size / 32)`.

The expansion cost is the difference between the cost at the new size and the cost
at the current size. If the access fits within already-allocated memory, the cost is 0.

## Example

    # Expanding from 0 to 32 bytes (1 word): 3×1 + 1²/512 = 3 gas
    # Expanding from 0 to 1024 bytes (32 words): 3×32 + 32²/512 = 98 gas
    # Expanding from 0 to 32768 bytes (1024 words): 3×1024 + 1024²/512 = 5120 gas

The quadratic term makes very large memory allocations prohibitively expensive,
providing a natural bound on memory usage.

# `memory_expansion_cost`

```elixir
@spec memory_expansion_cost(non_neg_integer(), non_neg_integer(), non_neg_integer()) ::
  non_neg_integer()
```

# `memory_expansion_cost_byte`

```elixir
@spec memory_expansion_cost_byte(non_neg_integer(), non_neg_integer()) ::
  non_neg_integer()
```

# `memory_expansion_cost_word`

```elixir
@spec memory_expansion_cost_word(non_neg_integer(), non_neg_integer()) ::
  non_neg_integer()
```

---

*Consult [api-reference.md](api-reference.md) for complete listing*
