1
    int  x; // Storage slot #0
    mapping (uint => uint)  y; // Storage slot #1
    uint []  z; // Storage slot #2
  
    function element() public  returns (uint a, uint b, uint c) {
      z.push(45);
      assembly {
          c:=mload(0)
      }
      
    }

z array is stored in storage. Running the below code returns c as 2. If I remove z.push(45), then c returns 0.

Why does it return 2 in case I have z.push(45). z is in storage, so why is it related to 0th address of memory(heap) ? I know 0th address is scratch space for hashing methods in memory, but i am curious why solidity stored number 2 in memory(heap) after doing z.push(45).

  • There are two differents operations mload reads from memory and sload from storage. I think for both you can read an 'invalid' position and they will return 0. – Ismael Oct 2 at 15:32
  • why does the above example return 2 ? that's the interesting one – Nika Kurashvili Oct 2 at 15:34
  • From the official documentation memory at address 0-64 is used as scratch pad for other operations so it is garbage. – Ismael Oct 2 at 15:37
  • yeah, i get that, but it's interesting why z.push(45) causes 2 to be put into that memory's address – Nika Kurashvili Oct 2 at 15:39
  • 1
    The reason 2 is at memory address 0 is because to store something 45 in z it needs to calculate the slot used by z, which is keccak256(2) – Ismael Oct 2 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.