Solidity – What Happens If Free Memory Pointer Is Not Updated in Assembly?

assemblysolidity

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.

Best Answer

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.