Skip to content

Memory leak with ndarray as function arg in Cython #13237

Closed
@ArtificialQualia

Description

@ArtificialQualia

When using an ndarray as an arg to a cdef function, and that ndarray is not used in the function, that object is never properly garbage collected and causes a memory leak.

If the ndarray is used in the function, it is collected properly.

Reproducing code example:

memleak.pyx

import numpy as np
cimport numpy as cnp
from numpy cimport ndarray
cnp.import_array()

cdef inline void caller():
    cdef:
        ndarray[int] x
    x = np.asarray(range(10000))
    dont_use_x(x)

cdef inline void dont_use_x(ndarray[int] x):
    pass

while True:
    caller()

setup.py:

from distutils.core import setup
from Cython.Build import cythonize
import numpy

setup(
    ext_modules = cythonize("memleak.pyx"),
    include_dirs=[numpy.get_include()]
)

to run:

python setup.py build_ext --inplace
python
import memleak

Numpy/Python version information:

1.16.2 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]

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