Skip to content

BUG: release the input of casts to object when move_references is set (#33278) - #33294

Merged
charris merged 1 commit into
numpy:maintenance/2.5.xfrom
charris:backport-33278
Nov 11, 2026
Merged

charris merged 1 commit into
numpy:maintenance/2.5.xfrom
charris:backport-33278

Conversation

@charris

@charris charris commented Nov 11, 2026

Copy link
Copy Markdown
Member

Backport of #33278.

PR summary

A ufunc that writes StringDType results into an object array leaks memory once the array is larger than the iterator buffer (8192 elements). For example:

import numpy as np

n = 20000
first = np.array([f"first name number {i}" for i in range(n)], dtype="T")
last = np.array([f"a longer last name, number {i}" for i in range(n)], dtype="T")
full = np.empty(n, dtype=object)
np.add(first, last, out=full, casting="unsafe")

LeakSanitizer reports on main:

ERROR: LeakSanitizer: detected memory leaks

Direct leak of 450560 byte(s) in 8192 object(s) allocated from:
    #0 in malloc
    #1 in NpyString_newemptysize
    #2 in load_new_string
    #3 in add_strided_loop(PyArrayMethod_Context_tag*, char* const*, long const*, long const*, NpyAuxData_tag*)
    #4 in execute_ufunc_loop
    #5 in PyUFunc_GenericFunctionInternal
    #6 in ufunc_generic_fastcall

SUMMARY: AddressSanitizer: 450560 byte(s) leaked in 8192 allocation(s).

The cast to object is supposed to clear its input when it is asked to move references, which is how these buffers get released. _strided_to_strided_any_to_object called the clear function with its loop counter after the loop had counted it down to zero, so nothing was cleared. The same bug leaks references when the buffer is a structured dtype with object fields.

Pass the original element count to the clear function, and also clear the input when converting an element fails partway through.

The existing tests write buffers that hold references back into numeric and structured arrays, but never into an object array, so nothing covered this cast. I extended test_iter_buffered_cast_structured_type with a refcount check that fails on main, and test_nditer_distinct_allocators with a StringDType buffer written back to an object array.

@charris charris added this to the 2.5.5 release milestone Nov 11, 2026
@charris charris added 00 - Bug 08 - Backport Used to tag backport PRs component: numpy.strings String dtypes and functions labels Nov 11, 2026
@charris
charris merged commit 0925c9b into numpy:maintenance/2.5.x Nov 11, 2026
99 of 100 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

00 - Bug 08 - Backport Used to tag backport PRs component: numpy.strings String dtypes and functions

2 participants