It is worth noting that as of solc v0.6.0, this "hack" is no longer viable:
Syntax:
length
member of arrays is now always read-only, even for storage arrays.
Using solc v0.6.0 or higher for the code above, you'd get a compilation error:
Member "length" is read-only and cannot be used to resize arrays
The only ways to impact the length of dynamic arrays in solidity are via:
- The
push
keyword (increment the length of the array by one) - The
pop
keyword (decrement the length of the array by one) - The
delete
keyword (reset the length of the array to zero)
And of course, pop
reverts when the length of the array is already zero.
So the overflow-trick that this challenge relies on is no longer viable in solidity.
You can still achieve that "hack" in your contract, but you'd need to implement it in assembly.
There are 4 different array types to handle:
- A dynamic array in storage, for example,
uint256[] public arr
- A dynamic array in memory, for example,
uint256[] memory arr
- A static array in storage, for example,
uint256[10] public arr
- A static array in memory, for example,
uint256[10] memory arr
For a dynamic array in storage, you can use either one of the following options:
assembly { sstore(arr.slot, new_length) }
assembly { sstore(arr.offset, new_length) }
For a dynamic array in memory, you can use the following option:
assembly { mstore(arr, new_length) }
For a static array, whether it's in storage or in memory, I'm not too sure how to achieve that...