0

I wrote this simple function to take an array of strings and eliminate duplicates, but it reverts with supplied parameters ["a","b","c"]. I thought it might have something to do with the equals functions (compares two string), but that runs fine on its own. In the debugger, it hangs on the assignment statement shown below, which comes prior to the equals function call.

Any thoughts appreciated.

pragma solidity >=0.7.0 <0.9.0;
contract Tester  {
    
    function dedupeKeys(string[] memory keys) public pure returns(string[] memory) {
       
        string[] memory deduped;
         if (keys.length == 0) return deduped;  
        bool found;
        string memory key;
        key = keys[0];
        deduped[0] = key;   //REMIX DEBUGGER HANGS HERE.            
        for(uint i=1; i<keys.length; i++) {
            found = false;
            key = keys[i];
            for(uint j=0; j<keys.length; j++) {
                if(equal(deduped[j], key)) {
                   found=true; 
                }
            }
            if (!found) {
                deduped[deduped.length]=key;
            }
        }
        return deduped;
    }
    
    function equal(string memory _base, string memory _value)
        internal
        pure
        returns (bool) {
        bytes memory _baseBytes = bytes(_base);
        bytes memory _valueBytes = bytes(_value);

        if (_baseBytes.length != _valueBytes.length) {
            return false;
        }

        for (uint i = 0; i < _baseBytes.length; i++) {
            if (_baseBytes[i] != _valueBytes[i]) {
                return false;
            }
        }

        return true;
    }

}
GGizmos
  • 3,443
  • 4
  • 27
  • 72

1 Answers1

0

You're trying to access an out-of-bounds array index.

This line creates the array with 0 items:

string[] memory deduped;

And here, you're trying to access the 1st item (index 0):

deduped[0] = key;   //REMIX DEBUGGER HANGS HERE.  

In the current Solidity version (0.8.x), it's not possible to resize a memory array. So you need to create it with the correct size, and calculate the size beforehand. See this answer for code example.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Thanks petr. Surprised it didn't trigger a compiler error. Didn't realize you couldn't have dynamics arrays in memory. But I guess that's why .push doesn't work for memroy arrays either. – GGizmos Aug 28 '21 at 21:25
  • @GGizmos Thats' correct, `push()` is available only on storage arrays - not memory. – Petr Hejda Aug 28 '21 at 21:41