Skip to content

fix(_gr): free strings returned by gr_get_str - #463

Open
RFT-SIRM wants to merge 1 commit into
flintlib:mainfrom
RFT-SIRM:fix/gr-get-str-memory-leak
Open

RFT-SIRM wants to merge 1 commit into
flintlib:mainfrom
RFT-SIRM:fix/gr-get-str-memory-leak

Conversation

@RFT-SIRM

@RFT-SIRM RFT-SIRM commented Dec 5, 2026

Copy link
Copy Markdown

Summary

This PR fixes a memory leak in the generic-ring string conversion path.

The gr_ctx.to_str() method calls FLINT's gr_get_str() to obtain a C string, copies it into a Python bytes object, and decodes it as UTF-8. However, the original string allocated by FLINT was never released.

Since gr.__repr__() delegates to gr_ctx.to_str(), repeatedly calling repr() or str() on generic-ring elements causes native heap memory to accumulate.

The fix ensures that the FLINT-allocated string is released using flint_free() in a finally block. This guarantees cleanup even if UTF-8 decoding raises an exception.

Technical details

  • Import flint_free from flint.flintlib.functions.flint.
  • Preserve the existing string conversion behavior.
  • Release the C-allocated buffer after copying and decoding it.
  • Use try/finally to guarantee resource cleanup.

Scope

This change addresses the generic-ring gr_get_str() path in src/flint/types/_gr.pxd.

It is separate from the previously fixed memory leak in the fmpz_mpoly, fmpq_mpoly, fmpz_mod_mpoly, and nmod_mpoly string conversion methods (PR #436). The generic-ring conversion path was not covered by that fix.

Validation

The FLINT memory ownership convention was checked against its API and existing FLINT callers, which release strings returned by gr_get_str() using flint_free().

The generic-ring string conversion is exercised by the existing doctests.

A local compiled test run has not been performed for this change. The Cython build and test suite should be validated by GitHub Actions.

Reasoning framework

SIRM (Synthetic Intelligence Reasoning Model) was used as the reasoning framework for investigating the codebase, identifying the memory leak, and analyzing the proposed correction.

The contribution focuses on fixing the identified resource-management defect while preserving the existing public behavior.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant