2

Learning Solidity latest version 0.5.0. And having bit confusion about data location rules.

It says that,

Assignments from memory to memory only create references. This means that changes to one memory variable are also visible in all other memory variables that refer to the same data.

I'm trying to understand it with an example

pragma solidity ^0.5.0;

contract Locations {

    function doSomething() public pure returns (uint[] memory) {

    uint[] memory localMemoryArray1 = new uint[](3);
    localMemoryArray1[0] = 4;
    localMemoryArray1[1] = 5;
    localMemoryArray1[2] = 6;

    uint[] memory localMemoryArray2 = localMemoryArray1;
    delete localMemoryArray1; 
    return localMemoryArray2;
  }
}

However, this returns value 4,5,6. As it is a reference type, it should return 0,0,0. Not sure if its my misunderstanding.

Further changes as per following code works as doc stated

pragma solidity ^0.5.0;

contract Locations {

    function doSomething() public pure returns (uint[] memory) {

    uint[] memory localMemoryArray1 = new uint[](3);
    localMemoryArray1[0] = 4;
    localMemoryArray1[1] = 5;
    localMemoryArray1[2] = 6;

    uint[] memory localMemoryArray2 = localMemoryArray1;
    localMemoryArray1[0] = 10; //<==== assigning new value
    return localMemoryArray2;
  }
} 

Above code returns 10,5,6, which is right!

1

From your second example, you should be able to deduce that delete only sets a value to zero, and doesn't delete a memory block or an array (as you're mistakenly expecting, out of your experience in "traditional" systems).

So delete localMemoryArray1 doesn't yield the effect that you're expecting to see.

Change it to:

delete localMemoryArray1[0]
delete localMemoryArray1[1]
delete localMemoryArray1[2]

And you'll see that your function returns an array of 3 zeros.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.