2

As far as I know, this is the standard way of the memory allocation in assembly:

assembly {
    let firstFreeMemoryPointer := mload(0x40)
    mstore(0x40, add(firstFreeMemoryPointer, numberOfBytesToAllocate)
}

But I've recently noticed the following example code in the Yul docs:

function allocate(size) -> ptr {
    ptr := mload(0x40)
    if iszero(ptr) { ptr := 0x60 }
    mstore(0x40, add(ptr, size))
}

Does anyone know if this step with checking ptr for zero value (if iszero(ptr) { ptr := 0x60 }) is required and when can this pointer actually be zero? :)

2
  • Yul is a low level language, if the contract was in solidity the free memory pointer should be initialized properly before entering the function.
    – Ismael
    Aug 10, 2022 at 4:53
  • I know, but I actually need to allocate memory directly in Yul Aug 10, 2022 at 11:12

1 Answer 1

2

Their code wants probably to keep the first two slots as scratch space, so they start the free memory at 0x60.

ptr := mload(0x40) is 0 the first time allocate is called. So without this line

if iszero(ptr) { ptr := 0x60 }

the code will write an object from the very first slot, overwriting the scratch space (and the free memory slot 0x40).

So this line is required only if you're writing a pure Yul object and not inline-assembly, because, as Ismael said, solidity already moves the free memory pointer before any other logic.


Note that to make this code Solidity-friendly, 0x60 should be 0x80. Check these commits:

https://github.com/ethereum/solidity/commit/6439955e834b1a1b6ae5f4a9aba857e04e4fefea

https://github.com/ethereum/solidity/commit/60d513c484c332dc816dad5ba17bf5c4da207e6f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.