2

When using inline assembly, the free memory pointer points initially to 0x80. Then let's say I store some value at that memory address like this:

assembly {
    let ptr := mload(0x40)
    mstore(ptr, "Bytes32 value")
}

This means that at the address 0x80, the bytes32 value is stored. Now let's say I end the assembly block and continue coding, and there is some operation that needs memory.

But the free memory pointer wasn't updated.

What will happen? Will it overwrite my data?

Thanks a lot hope it's clear.

1 Answer 1

4

What will happen? Will it overwrite my data?

Yes, if the code following adheres to solidity's memory model AND uses memory, it will start writing at the address returned by mload(0x40) and overwrite your data.

  function example() public pure returns (bytes32, string memory) {
        bytes32 myValue;

        assembly {
            // mload(0x40) is 0x80 initially
            mstore(mload(0x40), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }

        string memory myString = "hello";

        assembly {
            myValue := mload(0x80)
        }

        // myValue : 0x0000000000000000000000000000000000000000000000000000000000000005
        // myString : 'hello'
        return (myValue, myString);
    }

Here, myValue becomes 0x05 because the 32 bytes at 0x80 are now used by myString to store the length field. hello is 5 ASCII characters long, so its length is 5 bytes.

If you want to ensure that the memory space is secure (i.e., no side effects) then you must allocate the memory by incrementing the free memory pointer. Using memory above the free memory pointer but not allocating it is perfectly fine as long as you are treating that memory space as a scratch space. You can read more about it in the documentation.

I hope this answers your question.

1
  • Great explanation. Thanks a lot!
    – Kuly14
    Jul 19, 2022 at 11:24

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.