This code is taken from the solidity documentation.

library GetCode {
    function at(address addr) public view returns (bytes memory code) {
        assembly {
            // retrieve the size of the code, this needs assembly
            let size := extcodesize(addr)
            // allocate output byte array - this could also be done without assembly
            // by using code = new bytes(size)
            code := mload(0x40)
            // new "memory end" including padding
            mstore(0x40, add(code, and(add(add(size, 0x20), 0x1f), not(0x1f))))  // <--- This line
            // store length in memory
            mstore(code, size)
            // actually retrieve the code, this needs assembly
            extcodecopy(addr, add(code, 0x20), 0, size)

The free memory pointer is updated on this line, why is the padding added?

mstore(0x40, add(code, and(add(add(size, 0x20), 0x1f), not(0x1f))))

I think bytes and string are allocated in memory in bytes, not in words.

So why not simply write this? It seems to work correctly.

mstore(0x40, add(code, add(size, 0x20))

Any reason why padding should be added?

1 Answer 1


As you noted, I don't believe it is necessary. I think it's more of a good practice when it comes to memory because in solidity the data primitive is 32 bytes and many opcodes operate on chunks of 32 bytes. Perhaps there is also some underlying assumption that your data does not contains dirty bits, e.g. when loading a short string that fits into 32 bytes, although I can't say for sure.

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .