I've the following struct

struct Vote {
  uint amount;
  uint count;

Is it initialized when allocated in memory?

function boofar(uint val) public {
  Vote memory result;
  result.amount += val;

When explicitly initialized the gas cost is higher 1481 vs 1417.

1 Answer 1


They will be assigned zero values corresponding to type.

bool: false
uint: 0
int: 0
string: length 0
array: length 0
bytes: length 0
mapping: prohibited as memory variable

So, if you say result = ({ amount: 0, count: 0 }); you will create the same initial state at the cost of some useless work.

Hope it helps.

  • 2
    Is it documented this behavior? I found in the docs that I should not expect the free memory to be zeroed solidity.readthedocs.io/en/v0.5.10/…. In the warning it says The memory may or may not be zeroed out.
    – Ismael
    Aug 12, 2019 at 20:19
  • 1
    hmmm ... I've never seen not work as expected but that casts some doubt on things. The question just got interesting. Aug 12, 2019 at 22:09
  • 4
    Looking at the byte code the Solidity compiler emits, I'm pretty sure Solidity explicitly initializes the memory to 0. The warning in the documentation seems to be about directly manipulating memory yourself (where Solidity isn't doing any initialization).
    – user19510
    Aug 12, 2019 at 23:41
  • Thanks. That was my interpretation of the doc as well and yet the way it is worded left me with doubt. Aug 13, 2019 at 4:35
  • @smarx I think your comment is the right answer I was looking for. It should be good to update solidity docs to clarify this.
    – Ismael
    Aug 13, 2019 at 15:03

Your Answer

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

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