I have two little tests in which I'm trying to return bytes
that are populated via inline assembly. It works when I'm using a pre-defined return variable, but I'm getting a buffer overrun when I try to do it all in inline assembly. What am I missing here?
pragma solidity ^0.8.4;
contract AssemblyTest {
function working() external view returns (bytes memory res) {
assembly {
res := mload(0x40) // get free memory pointer
mstore(res, 0x40) // length: 64 bytes
mstore(add(res, 0x20), 1) // first 32 bytes
mstore(add(res, 0x40), 2) // second 32 bytes
mstore(0x40, add(res, 0x60)) // update free memory pointer
}
}
function notWorking() external view returns (bytes memory) {
assembly {
let res := mload(0x40) // get free memory pointer
mstore(res, 0x40) // length: 64 bytes
mstore(add(res, 0x20), 1) // first 32 bytes
mstore(add(res, 0x40), 2) // second 32 bytes
mstore(0x40, add(res, 0x60)) // update free memory pointer
return (res, 0x60) // return 96 bytes (32 bytes length + 64 bytes data)
}
}
}
abi.encode()
did, but I was still confused about one thing (a 0x40 that I couldn't explain; probably an offset just like here).