when should you start writing to memory address mstore(0x40, x) and when to mstore(0x80, x)?
Some contracts that I've seen, for example this one https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol
They use the 0x40 memory address, but others use the 0x80.
What is the difference, and which one should I use?
Thanks a lot hope the question is clear.
Best Answer
If you are asking the question, you probably should write at the address returned by
mload(0x40)
, you can read more about the solidity memory layout in the documentation.This is what the code that you linked is doing :
Writing directly to
0x80
or any other fixed address is a possible optimization (because don't pay additional gas for anmload(0x40)
instruction) if you either :memory[0x40]
(0x80
is the initial value stored at0x40
)0x00
)In any case, if you intend to return / use the any allocated memory space, make sure to mark that memory as allocated by incrementing the free memory pointer :
I hope this answers your question.