hello, i would like to ask a suggestion. I have to create a simple smart contract where i have an array of strings (probably an array of struct with several strings). and at any contract call, i have to push a record inside this array. Since i would like this array to grow without fixing a size, my questions are:
-is it possible to add indefintely records to the array so not defining a size? (i fear overflows)
-is there a openzeppelin lib which i can use for being safer?
thank you
Mass
Hi @mssmx
The maximum length of an array in Solidity is 2**256-1
https://solidity.readthedocs.io/en/latest/types.html#arrays
This means that you can safely push elements on to the end of an array until the maximum length is reached.
You could add a check that the length of the array is less than the maximum length prior to pushing an element on to the array.
OpenZeppelin has a Counters library in drafts, though if using an array you can just use the length.
Generally speaking, when you push an element into an array, it will not overflow, cause 2**256-1 is really large enough, but it is better to check the array length.
Many thanks to all, i was worried by overflow but as you correctly pointed out, it is not the case coz the maximum length is really large.
You could add a check that the length of the array is less than the maximum length prior to pushing an element on to the array.
thank you very much also @abcoathup for this suggestion
It is not physically possible to increment a 256 bit counter with increments of one, so the length check can be safely skipped. Additionally, if you did have such a lengthy array, you would be inevitably clashing with some other state variable in your contract, so you’d have bigger issues than the length.
tl;dr: just push to the array and don’t care about the max length.