Solidity – Understanding and Using Storage Pointers in Blockchain Development

blockchainethereum-wallet-dappremixsoliditystorage-pointer

contract X{

   uint256 public x=2;
   uint256[] public array= [9,8];
   
   function X(){}
   
   function getLength() public constant returns(uint256){
      return array.length;
   }
   
   function modifyArray( uint256 _index, uint256 _value){
      array[_index]= _value;
   }
   
   function popLength(){
      array.length--;
   }
}

Roman Storm shows in this video how to change the variable x with using storage pointers in this video https://www.youtube.com/watch?v=gUqHgFuSsqg with using the modifyArray-function at the end and I couldn't get it. Can someone explain in a detailed and simple way what is happening under the hood here. Thanks in advance. The code belongs to him(in the link).

Best Answer

There isn't much to explain. An uint256[] public array in storage is organized as follow:

| length |   0   |   1   | ... | length-1 |

Each | X | represents a 32 bytes slot.

The problem was that old solidity version allowed an underflow when modifying the array's length.

For example array has 2 elements, so after calling popLength() two times length will be zero.

If called a third time it will be 115792089237316195423570985008687907853269984665640564039457584007913129639935 which is 2**256 - 1.

So with array[X] you could write almost anywhere in the contract storage.

Related Topic