Sub topic 8
How CPython obtains memory: pymalloc, arenas, pools, and blocks
This chapter assumes you know that CPython frees most objects through reference counting (see the earlier chapters on reference counting and the cyclic collector). It also assumes you can read short Python scripts and have a rough idea of what malloc does in C. The details below describe CPython 3.10 and later on a 64-bit platform. Constants differ in older versions, and I call out the differences where they matter.
Why CPython has its own allocator
A typical Python program creates and destroys huge numbers of small objects: integers, short strings, tuples, bound methods, small dictionaries. Calling the operating system's malloc and free for each of them would be slow, and it would waste memory on per-allocation bookkeeping.
CPython therefore puts a specialised allocator, pymalloc, in front of the system allocator. It handles small requests quickly and keeps them packed together. It does not handle large requests at all.
The rule is simple:
- A request of 512 bytes or less goes to pymalloc.
- A request larger than 512 bytes goes straight to the system
malloc.
This applies to the object allocator, PyObject_Malloc. Large objects, such as a list holding 100,000 items, never touch pymalloc's data structures.
Three allocator domains
CPython exposes three families of allocation functions, called domains.
| Domain | Typical functions | Used for |
|---|---|---|
| Raw | `PyMem_RawMalloc` | Memory needed without the GIL held, or very early in startup |
| Memory | `PyMem_Malloc` | General memory buffers owned by the interpreter |
| Object | `PyObject_Malloc` | Python objects |
In current CPython releases, the memory and object domains both use pymalloc by default. The raw domain uses the system malloc. Extension authors should pick the domain that matches what they are allocating, and should never mix free with PyObject_Free.
The hierarchy: arenas, pools, blocks
Pymalloc organises memory in three levels.
- An arena is a large chunk requested from the operating system, normally through
mmapon Unix-like systems. In CPython 3.10 and later on 64-bit builds, an arena is 1 MiB. Older versions used 256 KiB. - A pool is a fixed-size slice of an arena. In 3.10 and later a pool is 16 KiB. Older versions used 4 KiB, matching the typical virtual memory page size.
- A block is a slice of a pool. Every block in one pool has the same size.
Because all blocks in a pool have one size, a pool needs no per-block headers. Finding space for a new object means taking one block from the right pool, which is very cheap.
Size classes
Pymalloc does not make a block of exactly the requested size. It rounds the request up to a size class. Since CPython 3.8 on 64-bit platforms, size classes are multiples of 16 bytes: 16, 32, 48, and so on up to 512. That gives 32 classes.
The rounding is a small calculation:
def size_class(nbytes):
"""Return the block size pymalloc would use, or None for large requests."""
if nbytes <= 0 or nbytes > 512:
return None
return ((nbytes + 15) // 16) * 16
for request in (1, 16, 17, 40, 100, 512, 513):
print(request, "->", size_class(request))Running it prints:
1 -> 16
16 -> 16
17 -> 32
40 -> 48
100 -> 112
512 -> 512
513 -> NoneThe leftover space inside a block is internal fragmentation. A 17-byte request wastes 15 bytes. This is the cost of speed and simplicity, and on average it is small compared with the savings.
How a pool works
Each pool starts with a small header, about 48 bytes on a 64-bit build. The header records the size class, the pool's neighbours in a linked list, and the head of a free list. The free list is a singly linked list threaded through the free blocks themselves. A free block stores a pointer to the next free block, so the bookkeeping costs no extra memory.
A pool is always in one of three states:
- used: some blocks are allocated and some are free.
- full: every block is allocated.
- empty: every block is free, so the pool can be reused for any size class.
Pymalloc keeps an array of "used" pools indexed by size class. To allocate, it looks up the pool for the request's class and pops the head of its free list. If the pool becomes full, it leaves the list. If a block in a full pool is freed, the pool rejoins the list for its class. If every block in a pool is freed, the pool becomes empty and goes back to its arena for reuse by any size class.
Observing the allocator
sys.getallocatedblocks() returns the number of memory blocks currently allocated by pymalloc. It lets you watch small allocations come and go.
import sys
before = sys.getallocatedblocks()
data = [object() for _ in range(10_000)]
after = sys.getallocatedblocks()
print(after - before >= 10_000) # True: each object() takes one block
del data
final = sys.getallocatedblocks()
print(abs(final - before) < 100) # True: the blocks were returnedThe list itself is about 80 KB, which is over 512 bytes, so it comes from the system malloc and does not appear in this count. Only the 10,000 small objects do.
For the full picture, call sys._debugmallocstats(). It writes a table to standard error showing, for each size class, the number of pools, blocks in use, and free blocks. It also reports the number of arenas and the bytes in use versus bytes held. The leading underscore marks it as a CPython implementation detail, so do not depend on its output format in programs.
import sys
sys._debugmallocstats()Returning memory to the operating system
Freeing a Python object does not always lower the process's memory use as reported by the operating system. Pymalloc can only release an arena back to the system when every pool in it is empty. A single surviving block pins its whole 1 MiB arena.
This is the main practical consequence of the design:
- A program that allocates millions of small objects and frees most of them may keep much of that memory reserved.
- The freed blocks are not lost. Pymalloc reuses them for later allocations of the same size class, so the process does not keep growing.
- Long-lived objects scattered across arenas make the problem worse. Allocating many short-lived objects between long-lived ones leaves arenas with a few survivors each.
CPython reduces this effect by preferring to allocate from the most full arenas. That lets nearly empty arenas drain and become free. It cannot eliminate fragmentation entirely.
Changing or debugging the allocator
The PYTHONMALLOC environment variable chooses the allocators at startup.
| Value | Effect |
|---|---|
| `pymalloc` | Default on most builds: pymalloc for the memory and object domains |
| `malloc` | Use the system `malloc` for every domain, bypassing pymalloc |
| `debug` | Pymalloc plus checks that detect buffer overruns and use of freed memory |
| `malloc_debug` | System `malloc` plus the same debug checks |
Setting PYTHONMALLOC=malloc is useful when you run a tool such as Valgrind or AddressSanitizer. Those tools track each malloc call, and pymalloc's large arenas hide individual objects from them. Setting PYTHONMALLOC=debug is useful when you write a C extension and suspect memory corruption.
What to remember
- Requests of 512 bytes or less go to pymalloc. Larger ones go to system
malloc. - Memory is arranged as arenas (1 MiB in 3.10 and later), split into pools (16 KiB), split into equal-size blocks in 16-byte size classes.
- Free blocks form a linked list inside their pool, so allocation and freeing are fast pointer operations.
- An arena returns to the operating system only when all its pools are empty, so process memory can stay high after objects are freed.
sys.getallocatedblocks()andsys._debugmallocstats()show what pymalloc is doing, andPYTHONMALLOCchanges it.
Exercise
A program builds a list of 500,000 small tuples, then keeps every 1000th tuple and deletes the rest. The resident memory of the process barely drops, although about 99.9% of the objects are freed. Explain why, and say whether the memory is leaked.
Show answer
The tuples are small, so they live in pymalloc blocks inside pools inside arenas. The 500 survivors are spread across nearly all the arenas, so almost no arena has all of its pools empty. Pymalloc can return an arena to the operating system only when the whole arena is empty, so the process keeps the memory. It is not leaked: the freed blocks stay on pool free lists and are reused for later allocations of the same size class. Allocating the survivors together, or in a separate process, would let the arenas be released.
Exercise
Using the rounding rule in this chapter, what block size does pymalloc use for a 49-byte request, and how many bytes are wasted inside the block?
Show answer
Rounding 49 up to the next multiple of 16 gives 64, so the block is 64 bytes and 15 bytes are wasted.