牢记获取无效的vm错误操作码,有什么想法吗?

时间:2019-02-05 21:48:32

标签: solidity opcode

我正在尝试测试此简单合同以从数组中删除地址,但我一直收到此“无效操作码”错误。

contract C {
    address[] addrList;

    function addAddr(address addr) public{
       addrList.push(addr);
    }

    function deleteAddr(address addr)public {

        for(uint256 i = 0; i < addrList.length; i++) {
            if(addr == addrList[i]) {
                for(uint256 j = i; j < addrList.length; j++) 
                    addrList[j] = addrList[j + 1];

                     delete addrList[addrList.length - 1];
                     addrList.length--; // <== This gives Error: Expression has to be an lvalue.
             }

1 个答案:

答案 0 :(得分:1)

该错误即将到来,因为您正在将变量ji迭代到addrList.length-1。这会使addrList[j+1]超出索引。

您需要将ji迭代到addrList.length-2。可以通过将条件更新为j < addrList.length-1来实现。

pragma solidity ^0.5.3;

contract C { 

    address[] addrList;

    function addAddr(address addr) public{
        addrList.push(addr);
    }

    function deleteAddr(address addr) public {

        for(uint256 i = 0; i < addrList.length; i++) {
             if(addr == addrList[i]) {
                 for(uint256 j = i; j < addrList.length-1; j++) {
                     addrList[j] = addrList[j + 1];
                 }
                 //delete addrList[addrList.length - 1]; 
                 addrList.length--;
             }
        }
    }

    function returnList() view public returns (address[] memory) {
        return addrList;
    }

}

此外,您也不需要使用delete步骤,因为编译器会自行清理内存插槽。