HACK ANALYSIS 3 min read

Improper Array Deletion


Improper Array Deletion

What is an Array in Solidity?

An array is a data structure that stores a fixed-size sequential collection of elements of the same type. An array in Solidity might have a fixed size at compile time or variable size. The elements of a storage array can be of several sorts.

Arrays use indexes to access and refer to their elements. It works in the following way:

  1. 0 (Zero Based Indexing) The array’s initial entry has an index of zero.
  2. The first element of the array refers to index 1, which is known as one-based indexing.
  3. n (n Based Indexing) — An array’s base index can be selected based on the situation.

Improper Array Deletion in Solidity

Although removing an element from an array in Solidity can be simple, there are several complex components hidden behind it. In Solidity, we remove an element from an array using the “delete” function. However, the length and sequence of the array may not remain as expected. Consider the code below.

Inside the contract, we’ve created an array of integers and the functions getLength()and removeItem().

  1. FirstArray is an integer array.
  2. The RemoveItem()function removes a specified item from an index.
  3. The array’s length is determined by the getLength()function.

We will deploy the contract and measure the firstArray’s length. It contains five numbers inside it. Hence it is obvious that the result is 5. Now, if we delete the array index 2, we will see that the array length remains the same, just that the value at index 2has been set to zero.
If we query the array length again, it can be seen that the length remains constant.

Why did the array’s length remain constant?
The number from the array is not removed when using the delete function. In other words, the value of that index is removed and replaced with “0.” The array’s size will remain the same, but index 2 will now be zero. As seen in the image above, the 2nd index of the firstArray is called; it returned 0.

Best Techniques for Array Deletion in Solidity:

The following are the recommended methods for array deletion in solidity, which are also beneficial for smart contract security. Instead of “delete” and “.length=0”, use push and pop functions to interact with array elements.

  1. We can remove array elements by shifting them from right to left.

2. We can remove an array element by copying the last element into the place to remove

SolidityScan detects improper array deletion and safeguards your contracts from 100+ security vulnerabilities at a click of a button.

SolidityScan Improper Array Deletion

Conclusion:
Improper array deletion can lead to erroneous business logic and cause unexpected results. It is important to delete arrays correctly. SolidityScan detects improper array deletion and safeguards your contracts. Signup for a free trial at https://solidityscan.com/signup