Search code examples
solidity

Solidity memory in a function


Hi I am new to solidity and I am wondering why we use the keyword memory when declaring a function, what happens if we choose not to use it? For example

function createObject(string _name, uint _dna) public {
    object.push(Object(_name, _dna));
}

instead of

function createObject(string memory _name, uint _dna) public {
    object.push(Object(_name, _dna));

Solution

  • if you don't write it, easily it will give error

    Without the memory keyword, Solidity tries to declare variables in storage.

    Much like RAM, Memory in Solidity is a temporary place to store data whereas Storage holds data between function calls. The Solidity Smart Contract can use any amount of memory during the execution but once the execution stops, the Memory is completely wiped off for the next execution. Whereas Storage on the other hand is persistent, each execution of the Smart contract has access to the data previously stored on the storage area.

    That is, the structure of storage is set in stone at the time of contract creation based on your contract-level variable declarations and cannot be changed by future method calls. BUT -- the contents of that storage can be changed with sendTransaction calls. Such calls change “state” which is why contract-level variables are called “state variables”. So a variable uint8 storagevar; declared at the contract level can be changed to any valid value of uint8 (0-255) but that “slot” for a value of type uint8 will always be there.

    If you declare variables in functions without the memory keyword, then solidity will try to use the storage structure, which currently compiles, but can produce unexpected results. memory tells solidity to create a chunk of space for the variable at method runtime, guaranteeing its size and structure for future use in that method.

    memory cannot be used at the contract level. Only in methods.