← Writing

Where the Memory Goes

20 min readSystemsPythonCpythonCMemoryMalloc
Contents

A Python 3.7 process makes four million floats, 130 MB of resident memory, and then deletes all but one in every thousand. Four thousand floats are left, about 96 kilobytes of actual data. The process still uses 100 MB. Delete those last four thousand and it drops to 7 MB at once. Nothing leaked: the memory was in use, by the allocator’s bookkeeping rather than by the program, because CPython hands memory back to the operating system only in 256 KiB pieces, and only when every object in a piece is gone.

This post is about that allocator, pymalloc, which sits between almost every Python object and the C library. It has size classes, pools and arenas, which this post reads the bookkeeping of directly. It explains why memory doesn’t come back, what the C library does instead, the free lists that keep freed objects for later, and a debug mode that catches C code writing past the end of an object.

This is Part 5 of a series on the CPython runtime. Part 1 measured object sizes, and Part 4 predicted copy-on-write costs from the size classes this post explains. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.1, released on 20 October and built from its tag with Ubuntu 18.04’s gcc 7.3.0, in a virtual machine booting 18.04’s release kernel. The note at the end says exactly where and how.

Why not just malloc?

A Python program allocates small objects all the time: every integer result, every tuple of arguments, every bound method, every frame. Most are a few dozen bytes and live for microseconds. A general-purpose malloc has to handle any size, any lifetime and any thread, and carries some overhead per allocation for that: a header per chunk, and bins and locks to search. In 2000 Vladimir Marangozov wrote pymalloc for Python’s specific pattern, many small blocks of a few sizes, and since Python 2.3 it has been the default allocator for objects of 512 bytes or less. Anything bigger goes straight to the C library’s malloc.

The design is described in a long comment at the top of Objects/obmalloc.c:

 * For small requests, the allocator sub-allocates <Big> blocks of memory.
 * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the
 * system's allocator.
 *
 * Small requests are grouped in size classes spaced 8 bytes apart, due
 * to the required valid alignment of the returned address. Requests of
 * a particular size are serviced from memory pools of 4K (one VMM page).
 * Pools are fragmented on demand and contain free lists of blocks of one
 * particular size class. In other words, there is a fixed-size allocator
 * for each size class. Free pools are shared by the different allocators
 * thus minimizing the space reserved for a particular size class.

Three levels, from the bottom:

  • Blocks. Every request is rounded up to a multiple of 8 bytes, which gives 64 size classes, 8, 16, 24, … 512. A block is one allocation.
  • Pools. A pool is one 4 KiB page holding blocks of a single size class, plus a 48-byte header. Freed blocks go back on their pool’s own free list.
  • Arenas. An arena is 256 KiB, 64 pools, and is the unit pymalloc gets from and gives back to the operating system, with mmap and munmap.

So every small object has a size class, and from Part 1’s sizes you can predict them:

import sys

GC_HEAD = 24          # Part 1: containers carry the collector's header before id()

def block(obj):
    size = sys.getsizeof(obj)                    # includes the GC header for containers
    return size, ((size + 7) // 8) * 8 if size <= 512 else None

print("%-28s %9s %11s" % ("object", "getsizeof", "pymalloc block"))
for label, obj in [("1.5", 1.5), ("1000", 1000), ("2**64", 2**64), ("(1, 2)", (1, 2)),
                   ("[]", []), ("{}", {}), ("'abc'", "abc"), ("'a' * 100", "a" * 100),
                   ("'a' * 1000", "a" * 1000), ("object()", object()),
                   ("lambda: 0", lambda: 0)]:
    size, blk = block(obj)
    print("%-28s %9d %11s" % (label, size, blk if blk else "malloc"))
$ python3 classes.py
object                       getsizeof pymalloc block
1.5                                 24          24
1000                                28          32
2**64                               36          40
(1, 2)                              64          64
[]                                  64          64
{}                                 240         240
'abc'                               52          56
'a' * 100                          149         152
'a' * 1000                        1049      malloc
object()                            16          16
lambda: 0                          136         136

A float fits its class exactly, at 24 bytes. An int of 1000 wastes 4 of its 32 bytes, and the string 'abc' wastes 4 of 56. A 1,000-character string is past the 512-byte threshold and goes to the C library. For containers, getsizeof already includes the 24-byte GC header, which is part of the same allocation. The one row the last column gets wrong is {}. PyDict_New in 3.7 allocates an eight-slot key table separately from the dict object, and getsizeof adds the two together, so the 240 bytes are a 72-byte block for the dict and its GC header plus a 168-byte block for the table. getsizeof reports what an object accounts for, not how the allocator carved it.

A pool, read from Python

Pools are page-aligned, so the pool holding any small object starts at its address rounded down to 4 KiB, and the pool’s header is the first 48 bytes there. This is its definition:

struct pool_header {
    union { block *_padding;
            uint count; } ref;          /* number of allocated blocks    */
    block *freeblock;                   /* pool's free list head         */
    struct pool_header *nextpool;       /* next pool of this size class  */
    struct pool_header *prevpool;       /* previous pool       ""        */
    uint arenaindex;                    /* index into arenas of base adr */
    uint szidx;                         /* block size class index        */
    uint nextoffset;                    /* bytes to virgin block         */
    uint maxnextoffset;                 /* largest valid nextoffset      */
};

and with Part 1’s ctypes trick, the header of a live pool can be decoded field by field:

import ctypes, struct

floats = [float(i) + 0.5 for i in range(10)]          # ten new floats, made one after another
ids = [id(f) for f in floats]
print("ids:", [hex(i) for i in ids[:4]], "...")
print("gaps between consecutive floats:", [b - a for a, b in zip(ids, ids[1:])])

pool = ids[0] & ~4095                                  # pools are 4 KiB and 4 KiB aligned
hdr = ctypes.string_at(pool, 48)
count, freeblock, nextpool, prevpool, arenaindex, szidx, nextoffset, maxnextoffset = \
    struct.unpack("<QQQQIIII", hdr)
print("pool at", hex(pool))
print("  ref.count     =", count, "blocks in use")
print("  szidx         =", szidx, "-> block size", (szidx + 1) * 8)
print("  arenaindex    =", arenaindex)
print("  nextoffset    =", nextoffset, " maxnextoffset =", maxnextoffset)
print("  first float is", ids[0] - pool, "bytes into the pool; blocks fit:", (4096 - 48) // 24)
$ python3 pool.py
ids: ['0x7f225b5210f0', '0x7f225b5211c8', '0x7f225b521210', '0x7f225b521228'] ...
gaps between consecutive floats: [216, 72, 24, 24, 24, 24, 24, 24, 24]
pool at 0x7f225b521000
  ref.count     = 28 blocks in use
  szidx         = 2 -> block size 24
  arenaindex    = 0
  nextoffset    = 744  maxnextoffset = 4072
  first float is 240 bytes into the pool; blocks fit: 168

Everything agrees with the struct and the comment:

  • szidx 2 is the third size class, 24 bytes: the pool holds floats and anything else that rounds to 24.
  • The gaps. The last seven floats are exactly 24 bytes apart, consecutive blocks carved one after another. The first two weren’t. They reused blocks that had been freed earlier, because a freed block goes on the front of its pool’s free list (or on the float free list, below) and is handed out again before any fresh one.
  • nextoffset 744 marks where the never-used part of the pool starts: (744 − 48) / 24 = 29 blocks have been carved so far, and ref.count says 28 are in use, so one is on the free list. Blocks are carved lazily, only when the free list is empty, so a new pool costs nothing until it is used.
  • maxnextoffset 4072 is the offset of the last block that fits: 4096 − 24. A 24-byte pool holds (4096 − 48) / 24 = 168 blocks with 16 bytes left over.
  • arenaindex 0: this pool is in the first arena the interpreter allocated.

One 4 KiB pool of 24-byte blocks, to scale

The page holding the script's first float, drawn from its header: 64 bytes per row, 64 rows.

pool header, 48 Bthe script's ten floatsother carved blocksnot carved yet
pool
0x7f225b521000
ref.count
28 blocks in use
szidx
2 → 24-byte blocks
nextoffset
744: 29 blocks carved
maxnextoffset
4072: room for 168 blocks
arenaindex
0

Hover or focus a block for its offset.

The header counts blocks in use but not which ones: of the 29 carved, 28 are in use and one is on the pool's free list. The 16 bytes after the last block that fits are never used.

The leak: memory that doesn’t come back

Pools return to their arena when their last block is freed, and an arena returns to the operating system only when all 64 of its pools are free. Here’s the case the C code lists as the first of four after a pool empties:

    /* All the rest is arena management.  We just freed
     * a pool, and there are 4 cases for arena mgmt:
     * 1. If all the pools are free, return the arena to
     *    the system free().
     * 2. If this is the only free pool in the arena,
     *    add the arena back to the `usable_arenas` list.
     * 3. If the "next" arena has a smaller count of free
     *    pools, we have to "slide this arena right" to
     *    restore that usable_arenas is sorted in order of
     *    nfreepools.
     * 4. Else there's nothing more to do.
     */

(The comment says free(), but in this build arenas come from mmap and go back with munmap.) So one live 24-byte object anywhere in an arena keeps the whole 256 KiB mapped. To watch it, this script reads the resident size from /proc/self/status, and the number of arenas from sys._debugmallocstats(), which prints the allocator’s own statistics to C’s stderr:

import gc, os, re, sys

def rss_mb():
    for line in open("/proc/self/status"):
        if line.startswith("VmRSS:"):
            return int(line.split()[1]) / 1024

def arenas():
    # _debugmallocstats writes to C stderr; read it back through a pipe
    r, w = os.pipe()
    saved = os.dup(2); os.dup2(w, 2)
    sys._debugmallocstats()
    os.dup2(saved, 2); os.close(w)
    text = os.read(r, 1 << 20).decode()
    os.close(r)
    m = re.search(r"# arenas allocated current\s*=\s*([\d,]+)", text)
    return int(m.group(1).replace(",", "")) if m else 0       # 0: pymalloc is not in use

N = 4000000
def report(step):
    print("%-38s RSS %7.1f MB   arenas %5d" % (step, rss_mb(), arenas()))

report("start")
data = [float(i) for i in range(N)]
report("4M floats")
del data
report("deleted all")
data = [float(i) for i in range(N)]
report("4M floats again")
keep = data[::1000]
del data
report("kept 1 in 1000 (4,000 floats)")
del keep
report("deleted those too")
$ python3 rss.py
start                                  RSS     6.3 MB   arenas     8
4M floats                              RSS   130.2 MB   arenas   380
deleted all                            RSS     7.0 MB   arenas     9
4M floats again                        RSS   130.1 MB   arenas   380
kept 1 in 1000 (4,000 floats)          RSS    99.8 MB   arenas   380
deleted those too                      RSS     7.1 MB   arenas     9

(MB is MiB here, as /proc reports KiB.)

Step by step:

  • 4M floats: 130 MB. Four million 24-byte floats are 91.6 MiB. An arena holds 64 pools of 168 floats, 10,752 floats, so they need 372 arenas, and the 380 measured include the interpreter’s own. The list’s array of four million pointers, 30.5 MiB, is bigger than 512 bytes, so it came from the C library, which mmaps large blocks directly.
  • Deleted all: 7 MB. Every arena emptied, so pymalloc unmapped 371 of them, and freeing the list unmapped its array. This is the good case: since Python 2.5, pymalloc does give memory back. Before 2.5, arenas were never freed at all.
  • Kept 1 in 1000: 99.8 MB. The pointer array went back, 30.5 MiB. But the 4,000 survivors are spread evenly through the 4 million, about 11 per arena, so not one arena is empty, and all 380 stay mapped. Four thousand floats, 94 KiB of data, held 95 MiB.
  • Deleted those too: 7 MB. With the last survivors gone, every arena empties at once.

That’s the classic Python memory complaint: “I deleted my big data structure and the process didn’t shrink.” What survives decides, and not how much of it. A cache that keeps a few objects from every batch, a long-lived log record created during a load phase, the interned strings created while parsing: any of them can pin the arenas that were filled at the same time. Nothing in Python can move an object to compact them, because the C API promises objects never move.

The C library does worse

PYTHONMALLOC=malloc (new in 3.6) tells CPython to skip pymalloc and send every allocation to the C library, glibc 2.27 here. Same script:

$ PYTHONMALLOC=malloc python3 rss.py
start                                  RSS     6.3 MB   arenas     0
4M floats                              RSS   159.3 MB   arenas     0
deleted all                            RSS   128.8 MB   arenas     0
4M floats again                        RSS   159.2 MB   arenas     0
kept 1 in 1000 (4,000 floats)          RSS   128.8 MB   arenas     0
deleted those too                      RSS   128.8 MB   arenas     0

Two differences, both glibc’s. Four million floats take 29 MB more, because glibc’s smallest useful chunk for a 24-byte request is 32 bytes (an 8-byte size header plus 16-byte alignment), so every float costs a third more than in pymalloc. And deleting everything gave back only the pointer array. glibc’s small chunks come from one contiguous heap that it grows with brk, and freed chunks go onto glibc’s own free lists for reuse. It can shrink the heap only from the top, and in this run it didn’t shrink it at all. A program that frees everything still holds its peak, which is worse than pymalloc’s worst case. So pymalloc’s arenas are not only faster. Here they were the only way the memory came back.

Resident memory after each step, two allocators

Python 3.7.1 on Linux 4.15: four million floats, deleted, made again, then all but one in a thousand deleted.

pymalloc (the default)PYTHONMALLOC=malloc (glibc)
start8 arenas
6.3
6.3
4M floats380 arenas
130.2
159.3
deleted all9 arenas
7.0
128.8
4M floats again380 arenas
130.1
159.2
kept 1 in 1000380 arenas
99.8
128.8
deleted those too9 arenas
7.1
128.8

Hover or focus a bar for details.

MiB resident (VmRSS). With pymalloc, emptied arenas are unmapped at once, but 4,000 survivors spread through all 380 arenas keep every one; with glibc, nothing of the small objects came back even when all of them were deleted.

They are faster too, on the hot path of making and freeing small objects:

import timeit
def churn():
    for i in range(1000000):
        t = (i, i)                    # small objects made and freed: the allocator's hot path
        l = [t]
print("%.3f s" % min(timeit.repeat(churn, number=1, repeat=7)))
$ python3 speed.py
0.023 s
$ PYTHONMALLOC=malloc python3 speed.py
0.027 s

Run in alternation twice, pymalloc took 0.023 s both times and glibc 0.027 and 0.026 s. That’s about 15% for a loop that does nothing but allocate. It’s less than you might expect, partly because the tuple and list structs in this loop come from free lists that bypass both allocators. Only the ints and the lists’ one-slot arrays reach the allocator.

Free lists: freed, but not given back

Several types keep their own stash of freed objects, in front of pymalloc. From the 3.7.1 source: floatobject.c keeps up to 100 floats, tupleobject.c up to 2,000 tuples of each length from 1 to 19 (PyTuple_MAXFREELIST, PyTuple_MAXSAVESIZE 20), listobject.c 80 list structs (PyList_MAXFREELIST), and dicts 80 more. The deallocator of such a type doesn’t call PyObject_Free. It pushes the object onto a static array or linked list, and the next allocation of that type pops it without asking anyone:

x = 12345
a = (x, x)
first = id(a)
del a
b = (x, "something else")             # a new 2-tuple: from the free list
print("new 2-tuple reuses the freed one's memory:", id(b) == first)
c = [1, 2, 3]
first = id(c)
del c
d = ["a"]
print("new list reuses the freed one's struct:   ", id(d) == first)
$ python3 freelist.py
new 2-tuple reuses the freed one's memory: True
new list reuses the freed one's struct:    True

This is why id() reuse, from Part 1, is so common: the free lists make it almost certain. And it has a consequence that the next section runs into: an object on a free list hasn’t really been freed. Whatever checks happen when memory goes back to the allocator haven’t happened yet.

Catching a C bug with PYTHONMALLOC=debug

Python can’t overflow a buffer, but C extension code can. The usual effect of writing one byte past an object is nothing at all, until something unrelated crashes much later. Here’s that byte, written with ctypes to stand in for an off-by-one in an extension:

import ctypes, sys
kind = sys.argv[1]
obj = float("1.5") if kind == "float" else bytes(20)
end = id(obj) + sys.getsizeof(obj)      # first byte after the object
ctypes.memset(end, 0, 1)                # one byte too far, like an off-by-one in a C extension
print("wrote one byte past a", kind)
del obj                                 # the last reference: the object is freed here...
print("deleted it")                     # ...or is it?
$ python3 overflow.py bytes
wrote one byte past a bytes
deleted it

Nothing happened. bytes(20) is 53 bytes, in a 56-byte block, so the stray byte landed in the rounding slack and hurt nobody. With a float it would have landed on the next float in the pool, silently changing its value or its reference count. Neither is detected.

PYTHONMALLOC=debug, usable in release builds since 3.6, wraps every allocation with guard bytes: 0xFB (FORBIDDENBYTE) on both sides of each block, checked when the block is freed.

$ PYTHONMALLOC=debug python3 -u overflow.py bytes
wrote one byte past a bytes
Debug memory block at address p=0x7fa2c7e0cc48: API 'o'
    53 bytes originally requested
    The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
    The 8 pad bytes at tail=0x7fa2c7e0cc7d are not all FORBIDDENBYTE (0xfb):
        at tail+0: 0x00 *** OUCH
        at tail+1: 0xfb
        at tail+2: 0xfb
        at tail+3: 0xfb
        at tail+4: 0xfb
        at tail+5: 0xfb
        at tail+6: 0xfb
        at tail+7: 0xfb
    The block was made by call #30738 to debug malloc/realloc.
    Data at p: 00 00 00 00 00 00 00 00 ... 00 00 00 00 00 00 00 00

Fatal Python error: bad trailing pad byte

Current thread 0x00007fa2c8e0a080 (most recent call first):
  File "overflow.py", line 7 in <module>
Aborted

The guard caught it at the del, on line 7, and printed exactly which byte was overwritten and with what. Now the float:

$ PYTHONMALLOC=debug python3 -u overflow.py float
wrote one byte past a float
deleted it
Debug memory block at address p=0x7f8c571482a8: API 'o'
    24 bytes originally requested
    The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
    The 8 pad bytes at tail=0x7f8c571482c0 are not all FORBIDDENBYTE (0xfb):
        at tail+0: 0x00 *** OUCH
        at tail+1: 0xfb
        at tail+2: 0xfb
        at tail+3: 0xfb
        at tail+4: 0xfb
        at tail+5: 0xfb
        at tail+6: 0xfb
        at tail+7: 0xfb
    The block was made by call #12200 to debug malloc/realloc.
    Data at p: 00 00 00 00 00 00 00 00 ... 00 00 00 00 00 00 f8 3f

Fatal Python error: bad trailing pad byte

Current thread 0x00007f8c571f6080 (most recent call first):
Aborted

The same corruption, but deleted it was printed, the program ran to its end, and the error came during interpreter shutdown, with no Python frame left to blame. del obj freed the float onto the float free list, not back to the allocator, so the guard bytes weren’t checked until shutdown emptied the free list. The last eight data bytes, ... f8 3f, are 1.5 as a little-endian double, the object’s own value still sitting in its block.

My first version of this script used b"x" * 20 instead of bytes(20). It also failed only at shutdown, for a different reason: Part 2’s constant folding turned the 20-byte product into a constant held by the module’s code object, so del obj didn’t drop the last reference. Two layers of the runtime, each deferring a free, each moving the error away from its cause.

What we covered

  • Objects of 512 bytes or less come from pymalloc: 64 size classes 8 bytes apart, 4 KiB pools of one size class each with a 48-byte header, and 256 KiB arenas from mmap. Bigger allocations go to the C library.
  • A pool’s header can be read from Python, and it showed blocks carved on demand, freed blocks reused first, and 168 floats to a pool.
  • An arena is returned only when all 64 of its pools are empty. 4,000 surviving floats spread through 4 million kept 95 MiB mapped, and deleting them returned it all.
  • With PYTHONMALLOC=malloc, glibc used 32 bytes per float instead of 24, and returned nothing of the small objects even after everything was deleted. pymalloc was also about 15% faster on a loop of small allocations.
  • Floats, tuples, lists, dicts and frames keep free lists of their own, so a freed object is often not freed yet.
  • PYTHONMALLOC=debug puts guard bytes around every block and caught a one-byte overflow, at the free for a bytes object and only at shutdown for a float on the free list.

The next post is about the other thing besides memory that every object shares: the lock that lets only one thread at a time touch any of them.

A note on the evidence

What I ran, and where. Everything ran on CPython 3.7.1, built from the v3.7.1 tag with Ubuntu 18.04’s gcc 7.3.0, in a KVM virtual machine (4 virtual CPUs, 4 GiB) booting 18.04’s release kernel 4.15.0-20-generic, on a minimal 18.04 userland from the release archive with glibc 2.27. Resident sizes are that kernel’s accounting. Each script was extracted from this page and run as shown.

The numbers. The memory figures are one run each. Page and arena counts are deterministic for a given build, and a rerun gave the same values to within 0.1 MB. The speed comparison is the best of seven runs, twice for each allocator, alternating, with nothing else running in the VM. Treat the 15% as an order of magnitude, not a constant. The classes.py block sizes are computed from getsizeof with 8-byte rounding, not read from the allocator. pool.py and the arena counts are read from the allocator itself.

What I worked out rather than read. That the first two floats in pool.py reused freed blocks is inferred from their addresses lying before the carved run, not from walking the free list. glibc’s behaviour is described from its general design, a brk heap that only shrinks from the top, and from the measurement; I didn’t instrument glibc to see why this run kept all of it. The 32-byte chunk size for a 24-byte request is glibc’s documented minimum on 64-bit and matches the extra 29 MB.

What I cited rather than ran. The C quoted here is from the v3.7.1 tag of Objects/obmalloc.c, and the free-list sizes from Objects/floatobject.c, Objects/tupleobject.c, Objects/listobject.c and Objects/dictobject.c. That arenas were never freed before Python 2.5, that pymalloc became the default in 2.3, and that PYTHONMALLOC arrived in 3.6 are from those releases’ “What’s New”. The authorship is the signature in obmalloc.c: “Vladimir Marangozov – August 2000”.

What I’d still change. Evenly spread survivors are the worst case for arenas, and real programs are usually somewhere between that and the best case. A better experiment would record an allocation trace from a real application and replay it. And I measured one glibc. Other C libraries and allocators such as jemalloc behave differently, and PYTHONMALLOC=malloc with LD_PRELOAD would make that comparison easy.

More