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
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.Here,
myValue
becomes0x05
because the 32 bytes at0x80
are now used bymyString
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.