[Ethereum] understanding mload assembly function

assemblysolidity

I am learning the inline assembly in solidity, i ve found the function mload(0x40) i am confused whith what this function does? did it reserve 4 Slot/word in memory or did it load the data stored in the address 0X40 or what?

Best Answer

mload(0xAB) Loads the word (32byte) located at the memory address 0xAB. e.g mload(0x60) loads the word located at 0x60 memory address.

let's code to understand more :

 function f ()  
    {

        assembly {
            let freemem_pointer := mload(0x40)
            mstore(add(freemem_pointer,0x00),"36e5236fcd4c61044949678014f0d085")
            mstore(add(freemem_pointer,0x20),"36e5236fcd4c61044949678014f0d086")
            let arr1:= mload(freemem_pointer) //read first string 
            mstore(add(freemem_pointer,0x40),arr1)


        }
    }

this results in the flowing memory state :

enter image description here

This previous code stores tow strings (two memory words 32bytes each) in the free memory space. The destinations memory addresses are obtained by adding an offset of 0bytes for the first and of 0x20 for the second to the free memory pointer address(located in the memory address 0x40).
in the EVM The 6 first words in the memory are reserved and the 0x40-0x50 memory words are allocated to the free memory pointer.

Details : mload and mstore are defined in details in the yellow paper :

enter image description here

[a...b) signifies the bytes of memory starting at position a up to (excluding) position b. however b] means b included