Do you need to zero-initialize every element when you allocate a new memory array in Solidity?
They are saying all differently.
YES – The memory may or may not be zeroed out. Because of this, one should not expect the free memory to point to zeroed out memory.
NO – As all variables in Solidity, the elements of newly allocated arrays are always initialized with theĀ default value.
These two answers are written on Solidity official doc.
Much confused!
And as always, I decided to make an experiment to give myself a clear answer.
function validateDynamicArrayInitialization() external pure {
uint256 c = 1234;
uint256 value;
uint256 pos;
uint256 nextPos;
// write non-zero value on the free memory area
assembly {
pos := mload(0x40)
mstore(add(pos, 0x20), c)
value := mload(add(pos, 0x20))
}
require(value == c);
// allocate new array
uint256[] memory amounts = new uint256[](2);
// validate it's initialized
require(amounts[0] == 0);
// reload free memory
assembly {
value := mload(add(pos, 0x20))
}
require(value == 0);
// validate free memory pointer updates
assembly {
nextPos := mload(0x40)
}
require(pos + (32 * (amounts.length + 1)) == nextPos);
// manipulate array
assembly {
mstore(add(pos, 0x20), c)
}
require(amounts[0] == c);
}
It passes without an exception.
As you see, it’s redundant to initialize the newly created array.
Sorry, the comment form is closed at this time.