PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

[FIXED] What is the difference between "memory" and "storage" keyword

 July 28, 2022     blockchain, memory, solidity, storage     No comments   

Issue

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?


Solution

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.



Answered By - Yilmaz
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing