Pages that are no longer in use are kept on the freelist, for SQLite to reuse before it makes the file longer. The database header gives the first trunk page at offset 52 and the number of free pages, trunks included, at offset 56.
Trunk pages
The header’s first free page is a trunk page. Each trunk lists free pages and points to the next trunk. Numbers are in the file’s byte order.
| Offset | Size | Type | Name | Description |
|---|---|---|---|---|
| 0 | 4 | u32 | next trunk | The next trunk page, or 0 on the last. |
| 4 | 4 | u32 | count | How many free page numbers follow, at most 254 (the struct FreelistInfo starts here). |
| 8 | 4 × count | u32[] | free pages | The numbers of the free pages this trunk lists. 8 + 254 × 4 = 1,024, so 254 fill the page. |
To find every free page:
- Start at the header’s first free page. If it is 0, the freelist is empty.
- Count the trunk itself, then read its count and that many page numbers.
- Go to the next trunk, and stop at 0.
- The pages found, trunks included, should equal the header’s free page count.
When a page is freed, SQLite adds it to the first trunk’s list if there is room. Otherwise the freed page becomes the new first trunk, with its contents cleared. Reusing a page takes one from the first trunk’s list (the one nearest the page wanted) or, when that list is empty, the trunk itself.
Which release introduced trunk pages is not confirmed. SQLite 2.1.0 chained free pages directly, each page’s first 4 bytes giving the next. SQLite 2.8 still reads such a chain, since each page then reads as a trunk with a count of 0.
Free pages
The pages a trunk lists are free pages, sometimes called leaves. Their contents mean nothing: they may still hold whatever the page held before it was freed.