Safe to delete an array in a mapping?

Hey guys, here is a quick question on if it is safe to delete the entire mapped array in a mapping and create a new one. See the following snippet for an example.

I once read somewhere on dynamic arrays in a mapping that although the pointer is deleted, the values are not, therefore, the same mapping may return unexpected values. In this simple test, it worked fine, but would like to get in-depth explanations. Thanks.

// SPDX-License-Identifier: MIT

pragma solidity 0.8.9;


contract Test {
    mapping(uint256 => uint256[]) public _ideaPool;

    function add(uint256 epochId, uint256[] memory ideaIds) public {
        uint256[] storage ideas = _ideaPool[epochId];
        require(ideas.length == 0, "Invalid epochId");
        uint256 n = ideaIds.length;

        for (uint256 i = 0; i < n; i++) {
            ideas.push(ideaIds[i]);
        }
    }

    function update(uint256 epochId, uint256[] memory ideaIds) external {
        delete _ideaPool[epochId];
        add(epochId, ideaIds);        
    }
}

The documentation for delete states:

it can also be used on arrays, where it assigns a dynamic array of length zero or a static array of the same length with all elements set to their initial value

This means when you run delete _ideaPool[epochId] you're resetting the array length to 0 as well as resetting all existing members of the array to 0.

You need to be careful with this operation because it results in a potentially unbounded amount of operations (one storage write for each array member), and this is dangerous if the array length is user-controlled.

1 Like

Thanks @frangio. Always to the point and insightful.

1 Like