Question:

Does array memory destroy other variables in memory?

Benjamin: 2 weeks ago

I have been testing and found that data is destroyed as follows.

    function getFreeWallets2(  string mybonusname) public view returns ( uint length, uint  k1, uint  length1) {

    bytes32 bonusNameBytes32 = stringToBytes32(mybonusname);
    require(Bonuses[bonusNameBytes32].bonusExists, "Bonus does not exist");
      length = Wallets.length;
      length1 = getNumberWallets();
    address[]  memory    FreeWallets;
      k1=0;
    for(uint i = 0; i < length; i++)
    {
       address mywallet = Wallets[i];
       if (!WalletBonuses[mywallet][bonusNameBytes32].bonusExists)
       {
           FreeWallets[k1]=mywallet;
           k1++;
       }
    }



}

Outcome - the return is 0,0,0 even though Wallets has data in it.

When I comment out the allocation line for the array, then the return is 1,1,1 which shows the actual value.

This is the offending line -

FreeWallets[k1]=mywallet;

Somehow this causes the data to be overwritten and then the whole function does not work.

    function getFreeWallets2(  string mybonusname) public view returns ( uint length, uint  k1, uint  length1) {

        bytes32 bonusNameBytes32 = stringToBytes32(mybonusname);
        require(Bonuses[bonusNameBytes32].bonusExists, "Bonus does not exist");
          length = Wallets.length;
          length1 = getNumberWallets();
        address[]  memory    FreeWallets; 
          k1=0;
        for(uint i = 0; i < length; i++)
        {
           address mywallet = Wallets[i];
           if (!WalletBonuses[mywallet][bonusNameBytes32].bonusExists)
           {
            //   FreeWallets[k1]=mywallet; <==== Commented out
               k1++;
           }
        }



    }

I tried all kinds of combinations with storage and memory and it just throws errors all the time regarding push or something else.

The design is easy enough (just to filter an array) but solidity has some issues in handling this.

Has anyone any suggestions?

Answer:
Charlotte: 2 weeks ago

I think the problem is since you are not allocating sufficient space to a dynamic array FreeWallets,mywallet is not getting inserted an array.

Allocate sufficient space to FreeWallets array and then insert an element. For that, you need to change the code as follows while defining array FreeWallets-

address[] memory FreeWallets = new address[](Wallets.length);

Hope it helps.