Skip to content

str() leaks at fmpz_mpoly, fmpq_mpoly, fmpz_mod_mpoly, nmod_mpoly #435

Closed

Description

@UriKH

str() of fmpz_mpoly, fmpq_mpoly, fmpz_mod_mpoly, nmod_mpoly leaks the C string from *_get_str_pretty

The str() method of the four multivariate types never frees the buffer
returned by *_mpoly_get_str_pretty.

# src/flint/types/fmpz_mpoly.pyx:736 (0.9.0 and main)
def str(self):
    cdef bytes s = <bytes> fmpz_mpoly_get_str_pretty(self.val, self.ctx.c_names, self.ctx.val)
    ...

The <bytes> cast copies the char * into a new Python bytes object, and the
original buffer (from flint_malloc in _fmpz_mpoly_get_str_pretty) is lost.
The same line appears in fmpq_mpoly.pyx:762, fmpz_mod_mpoly.pyx:748 and
nmod_mpoly.pyx:722.

Reproduction (python-flint 0.9.0, FLINT 3.6.0, macOS arm64, Python 3.12):

import flint, psutil, gc
ctx = flint.fmpz_mpoly_ctx.get([f"x{i}" for i in range(8)], "lex")
x0 = ctx.gens()[0]
p = psutil.Process()
gc.collect(); r0 = p.memory_info().rss
for _ in range(1_000_000):
    str(x0)
gc.collect(); print((p.memory_info().rss - r0) / 2**20, "MB")   # ~61 MB, linear in N

Measured leak per call for every type and path: python-flint 0.9.0, FLINT 3.6.0,
macOS; live C heap from malloc_zone_statistics; identical at N = 100k, 200k and 400k.

type x.str()
fmpz_mpoly 112 B
fmpq_mpoly 128 B
fmpz_mod_mpoly 96 B
nmod_mpoly 80 B

The leak per call grows with the size of the string (variables, terms, digits):

poly variables leak per str()
generator 3 32 B
generator 8 64 B
(sum of gens + 5)^4, 35 terms 3 640 B
(sum of gens + 5)^4, 495 terms 8 ~25.6 KB

Suggested fix: keep the char *, decode it, then flint_free it, as
fmpz.str() already does (src/flint/types/fmpz.pyx lines 185–189:
fmpz_get_str … finally: flint_free(s)), e.g.

cdef char *cs = fmpz_mpoly_get_str_pretty(self.val, self.ctx.c_names, self.ctx.val)
try:
    s = (<bytes> cs).decode()
finally:
    flint_free(cs)

Impact: in our code str(generator) is called thousands of times
per computation, only to get variable names. Long-running worker processes grew
by ~0.3–0.5 MB per task (hundreds of MB over a run).

Activity

  1. added a commit that references this issue on Oct 22, 2026
    9b336d0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions