What is the difference between "memory" and "storage" keyword

Viewed 127
pragma solidity >=0.5.0 <0.6.0;

contract ZombieFactory {

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    function createZombie (string memory _name, uint _dna) public {
        // start here
    }

}

Here I am confused because as per this post https://ethereum.stackexchange.com/questions/1701/what-does-the-keyword-memory-do-exactly?newreg=743a8ddb20c449df924652051c14ef26

"the local variables of struct are by-default in storage, but the function arguments are always in memory". So does it mean that in this code when we pass string _name as a function argument, it will be assigned to memory or will it remain in the storage like all other state variables?

2 Answers

Storage store data in blockchain and it remains immutable. Memory store temporary variables, that included in functions(in this case _name) and their lifetime limited while executing this function. So when we pass string _name as a function argument, it will be assigned to memory, while your variable in struct(name) will be assingned to storage.

All the state variables are stored in storage permanently. It is like hard disk storage.

Memory is like RAM. When a contract finishes its code execution, the memory is cleared.

Sometimes after you declared a state variable, you want to modify it inside a function. For example you defined

 Zombie[] public zombies;

function createZombie (string memory _name, uint _dna) public {
        Zombie storage firstZombie=zombies[0]
        // mutate the name of the firstZombie
        firstZombie.name=_name
        // you have actually mutated state variable zonbies
    }

If you used memory keyword, you would be actually copying the value to the memory:

function createZombie (string memory _name, uint _dna) public {
            // firstZombie is copied to the memory
            // New memory is allocated.
            Zombie memory firstZombie=zombies[0]
            // mutate the name of the firstZombie
            firstZombie.name=_name
            return firstZombie
            // this did not mutate the state variable zombies
            // after returning allocated memory is cleared
        }

In solidity, function parameter variables are stored in memory.

Related