Could someone explain to me what exactly happens when I declare a storage pointer?

This example highlights the issue that I have encountered:

contract minimum {

  uint256[] a = [1,2,3,4];

  function createOffersAsList() public returns (uint256[]) {

    uint256[] storage b;
    uint256 i = 0;

    Logger("Before loop", b); 
    // What I expected it to return: '"Before loop", ""'
    // What it actually returns: '"Before loop", "1, 2, 3, 4"'
    while (i<4) {
    Logger("After loop", b);
    return b;
    // What I expected it to return: '"After loop", "1, 2, 3, 4"'
    // What it actually returns: '"After loop", "1, 2, 3, 4, 1, 2, 3, 4"'

  event Logger(string s, uint256[] u);

It seems to me, that when I declare b that it is automatically assigned to the storage of a. Why is that? I would have thought that it is just assigned to some free space?

And if I need to use a local dynamically sized array, how would this look like?

Thanks in advance and best regards, carbee

1 Answer 1


When you declare a storage variable, it's essentially a reference to some location in storage. Until you assign it to something, it points to location 0, which also happens to be the location of the first declared state variable (in this case a). You're basically using an uninitialized pointer.

See http://solidity.readthedocs.io/en/develop/types.html#data-location.

For your second question, you can allocate variable-length arrays in memory using the new keyword, but you can't resize them after creation.

See http://solidity.readthedocs.io/en/develop/types.html#allocating-memory-arrays.

  • Thanks a lot, that makes sense! Is there a way to initialize the pointer to another storage location that contains no values yet?
    – carbeer
    Jan 9, 2018 at 11:18
  • How would you find that storage again later? You could use a mapping or array.
    – user19510
    Jan 9, 2018 at 14:30
  • I would assume that the storage is characterized by the location (e.g. 0) and not the value that it contains?
    – carbeer
    Jan 9, 2018 at 15:13
  • I mean, for example, declare an array as a state variable, and then in your function, .push(...) to extend it and use the new element.
    – user19510
    Jan 9, 2018 at 15:17

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.