2

I have a solidity library that has a public function and it's returning a uint8[] array.

pragma solidity ^0.8.4;

library LibA {
    function getArray() public pure returns (uint8[] memory) {
        uint8[] memory arr;
        arr[0] = 100;
        ...

        return arr;
    }
}

Then I have a Solidity smart contract that references the library and calls the function trying to access the array defined in the library. The code looks like this.

pragma solidity ^0.8.4;

import "./LibA.sol";

contract SampleContract {

    function doSomething(uint8 _index) public pure returns (uint8) {
        return LibA.getArray()[_index];
    }
}

The code compiles just fine. I have a mocha unit test that is run using Hardhat to test the method and when I run the unit test I get the following exception.

Error: VM Exception while processing transaction: reverted with panic code 0x32 (Array accessed at an out-of-bounds or negative index)

I am quite new to Solidity and I'm having trouble understanding exactly what is the reason for the exception and how to resolve it. Some help would be greatly appreciated.

2 Answers 2

6

I've never worked with libraries before, however I believe the issue might be that you are trying to have a dynamically sized array in memory. This should be

uint8[] memory arr = new uint8[](arraySize);

in order to allocate the space in memory beforehand.

1
  • You are absolutely right. That was the issue. Thank you so much :) Nov 5, 2021 at 21:21
0

if you are using a dynamic array then instead of assigning the index, just push into the array.

pragma solidity ^0.8.4;

library LibA {
    function getArray() public pure returns (uint[] memory) {
        uint[] memory arr;

// change here

 arr.push(100);
        return arr;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.