Skip to content

Fix memory leak in pyopencv_to for path-like objects#28047

Merged
asmorkalov merged 3 commits intoopencv:4.xfrom
0AnshuAditya0:fix-pyos-fspath-memory-leak
Nov 26, 2025
Merged

Fix memory leak in pyopencv_to for path-like objects#28047
asmorkalov merged 3 commits intoopencv:4.xfrom
0AnshuAditya0:fix-pyos-fspath-memory-leak

Conversation

@0AnshuAditya0
Copy link
Copy Markdown
Contributor

This PR fixes a memory leak in pyopencv_to when handling path-like objects (e.g., pathlib.Path).
Problem:
PyOS_FSPath() returns a new strong reference, but the code was not calling Py_XDECREF to decrement it, causing a memory leak on every call with path-like arguments.
Solution:

Store the returned reference from PyOS_FSPath() in a separate variable path_obj
Call Py_XDECREF(path_obj) on all function exit paths (both success and error paths)
This ensures proper reference counting without changing the function's behavior

Testing:
The leak can be reproduced using the steps in issue #28046 with Python built with --with-address-sanitizer. This fix ensures the reference is properly released.
Fixes #28046

Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

✓ I agree to contribute to the project under Apache 2 License.
✓ To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
✓ The PR is proposed to the proper branch (4.x)
✓ There is a reference to the original bug report and related work (#28046)
NA There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
✓ The feature is well documented and sample code can be built with the project CMake

PyOS_FSPath returns a new strong reference that must be decremented.
Added proper reference counting by storing the returned value and
calling Py_XDECREF on all exit paths.

Fixes opencv#28046
@0AnshuAditya0
Copy link
Copy Markdown
Contributor Author

Thanks for fixing the scope issue! I see you've pushed the corrections directly - appreciate you taking the time to clean that up. I'll make sure to be more careful with preprocessor blocks in future contributions.

@0AnshuAditya0
Copy link
Copy Markdown
Contributor Author

It looks like the Windows x64 test failed due to a network error (ECONNRESET) rather than a code issue. The other CI checks have passed. Could someone restart this check when possible?

@asmorkalov asmorkalov merged commit 166f459 into opencv:4.x Nov 26, 2025
24 of 26 checks passed
@asmorkalov asmorkalov mentioned this pull request Dec 2, 2025
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.

Python: reference leak in pyopencv_to modules/python/src2/cv2_convert.cpp

2 participants