4

Below is the example using the anchor realloc constraint.

#[derive(Accounts)]
pub struct Example {
    #[account(mut)]
    pub payer: Signer<'info>,
    #[account(
        mut,
        seeds = [b"example"],
        bump,
        realloc = 8 + std::mem::size_of::() + 100,
        realloc::payer = payer,
        realloc::zero = false,
    )]
    pub acc: Account<'info, MyType>,
    pub system_program: Program<'info, System>,
}

The anchor-lang doc says:

The realloc::zero constraint is required in order to determine whether the new memory should be zero initialized after reallocation.

Note: Memory used to grow is already zero-initialized upon program entrypoint and re-zeroing it wastes compute units. If within the same call a program reallocs from larger to smaller and back to larger again the new space could contain stale data. Pass true for zero_init in this case, otherwise compute units will be wasted re-zero-initializing.

https://docs.rs/solana-program/latest/solana_program/account_info/struct.AccountInfo.html#method.realloc

https://docs.rs/anchor-lang/latest/anchor_lang/derive.Accounts.html

I don't really understand what the documentation explaination means. Could someone explain in more simple terms what "zero initialized" means and provide an example of when realloc::zero should be set to true?

1 Answer 1

3

zero-initialized means that all the bytes in memory will be initialized to 0x00. What this means depends on the type of data you have in there.

Let's say you have some integers in there, no matter if signed or unsigned, the zero-initialization means you will have the numeric value of 0 in these struct fields.

Say you have a counter field in the new data, telling you much many items you already sold. You would expect that to be 0 when you create it. Without zero initialization, you can have any random value in there. So it could 3,718 or -32,768. You would then have to make sure that you explicitly assign an initial value to your data, in all possible execution paths.

What the docs also say is that you only need to request zero initialization if you have used the memory before, then shrunk it, and then expanded it again. In that case, and only in that case, there can be random values.

If the memory is newly allocated, it is already zero-initialized by the Solana runtime, so you don't have to initialize it again.

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.