Gotchas

If a user doesn’t respect Solidity’s memory layout and use the free memory pointer, and tries to write to an arbitrary memory location, then serious bugs may occur

  • Example: storing a value in memory and reading the same value

function breakFreeMemoryPointer(uint256[1] memory foo)
        external
        pure
        returns (uint256)
    {
        assembly {
            mstore(0x40, 0x80) 
        }
        uint256[1] memory bar = [uint256(6)];
        return foo[0];
    }
  • foo should be stored at 0x80, and free memory pointer should be moved to 0xa0 (0x80 + 0x20)

  • but if we rewind it back to 0x80 and declare bar in memory, querying for foo will end up returning bar instead

The EVM does not try to pack datatypes smaller than 32 bytes

  • if you load something from storage into memory, it will be unpacked and take up 32 bytes, even if the initial storage variable is smaller than 32 bytes

Last updated