Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ethtool/ioctl: Use byref instead of cpointer when possible #1323

Merged
merged 1 commit into from
Mar 17, 2025

Conversation

JeThWifirst
Copy link
Contributor

According to the ctypes documentation 1, calling cpointer creates a new instance, and it seems to lead to memory leaks: "Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute".

The cpointer documentation 2 indicates that byref should rather be used when passing "a pointer to an object to a foreign function call".

Reproducer

The following reproducer shows the memory leak:

#!/usr/bin/python3
import psutil
from pyroute2.ethtool import Ethtool


def main():
    process = psutil.Process()
    memory = []

    with Ethtool() as ethtool:
        for idx in range(10001):
            ethtool._with_ioctl.change_ifname("enp11s0")
            ethtool._with_ioctl.get_statistics()
            if idx % 1000 == 0:
                memory.append(round(process.memory_info().rss / 1024 / 1024, 2))

    print(memory)


if __name__ == "__main__":
    main()

Without the fix, on my computer:

$ ./reproducer.py
[39.05, 50.42, 62.05, 73.92, 85.42, 96.92, 109.17, 120.67, 132.17, 143.55, 155.05]

With the fix, on my computer:

$ ./reproducer.py
[38.92, 39.05, 39.05, 39.05, 39.05, 39.05, 39.05, 39.05, 39.05, 39.05, 39.05]

According to the ctypes documentation [1], calling cpointer creates
a new instance, and it seems to lead to memory leaks: "Note that ctypes
does not have OOR (original object return), it constructs a new,
equivalent object each time you retrieve an attribute".

The cpointer documentation [2] indicates that byref should rather
be used when passing "a pointer to an object to a foreign function
call".

[1]: https://docs.python.org/3/library/ctypes.html#pointers
[2]: https://docs.python.org/3/library/ctypes.html#ctypes.pointer
@svinota svinota added the bug label Mar 17, 2025
@svinota
Copy link
Owner

svinota commented Mar 17, 2025

Oh, thanks! Merging tonight.

@svinota svinota added resource leak and removed bug labels Mar 17, 2025
@svinota svinota merged commit 70498b7 into svinota:master Mar 17, 2025
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants