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.

1 Answer 1

5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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