> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/solana-foundation/anchor/llms.txt
> Use this file to discover all available pages before exploring further.

# Space calculation

> Calculate account space requirements for Anchor programs

When initializing accounts, you must specify the space (size in bytes) required.

## Basic formula

```
space = 8 (discriminator) + account_data_size
```

## Type sizes

| Type       | Size (bytes)                |
| ---------- | --------------------------- |
| bool       | 1                           |
| u8/i8      | 1                           |
| u16/i16    | 2                           |
| u32/i32    | 4                           |
| u64/i64    | 8                           |
| u128/i128  | 16                          |
| Pubkey     | 32                          |
| String     | 4 + length                  |
| Vec\<T>    | 4 + (size\_of(T) \* length) |
| Option\<T> | 1 + size\_of(T)             |

## InitSpace derive

Use `InitSpace` for automatic calculation:

```rust theme={null}
#[account]
#[derive(InitSpace)]
pub struct Data {
    pub value: u64,        // 8
    pub owner: Pubkey,     // 32
    pub name: String,      // 4 + len
}

// Usage
#[account(init, payer = user, space = 8 + Data::INIT_SPACE)]
pub data: Account<'info, Data>
```

### String and Vec lengths

Specify max lengths with attributes:

```rust theme={null}
#[account]
#[derive(InitSpace)]
pub struct Data {
    #[max_len(50)]
    pub name: String,
    #[max_len(10)]
    pub items: Vec<u64>,
}
```

## Manual calculation

```rust theme={null}
#[account(init, payer = user, space = 8 + 32 + 8)]
pub data: Account<'info, Data>

#[account]
pub struct Data {
    pub owner: Pubkey,  // 32
    pub count: u64,     // 8
}
// Total: 8 (discriminator) + 32 + 8 = 48 bytes
```

## Best practices

<Tip>
  Always use `InitSpace` derive to avoid calculation errors.
</Tip>

<Warning>
  Allocate enough space for dynamic types (String, Vec) based on expected max size.
</Warning>
