Skip to main content
1 of 3

Why Vec::push giving memory allocation failed, out of memory error?

For example: I have a struct named Item

#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct Item {
  ...fields
}

and I am storing those items inside a PDA account named UserAccount

#[account]
pub struct UserAccount {
    pub owner: Pubkey,              
    pub items: Vec<Item>,
}

At the account initialization i am setting the account size to MAX_PERMITTED_DATA_INCREASE that means 10240 bytes.At this stage i am able store almost 115 items into the vector without any issue.

I have some logic in place that reallocates another 10240 bytes when there is not enough space to store another item. This part also works fine. At this stage account size is 20480 bytes.

After allocating the space second time,and when try to push new item, i get Program log: Error: memory allocation failed, out of memory. This error doesn't happen after immediate allocation. From my testing it looks like it throws this error randomly, sometimes i am able to push abother 10 items (125 total), some times 20(145 toal) items and after that it gives me this error.

From few other threads i came to know push method allocates the entire account's state, I am not sure what does that mean. If i am within the limit why that would be an issue.

So my question is why this error actually happening , even i have enough space for vector to grow and I think i am within the boundary of heap limit. What actually going on under the hood ?

Any Kind of help is really appreciated.