fix: memory leak in Option<T>::as_ptr

This commit is contained in:
David Hewitt 2022-02-11 22:17:00 +00:00
parent 08d983ba0d
commit c5ef24bbea
2 changed files with 20 additions and 2 deletions

View File

@ -84,6 +84,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix panic in `#[pyfunction]` generated code when a required argument following an `Option` was not provided. [#2093](https://github.com/PyO3/pyo3/pull/2093) - Fix panic in `#[pyfunction]` generated code when a required argument following an `Option` was not provided. [#2093](https://github.com/PyO3/pyo3/pull/2093)
- Fixed undefined behaviour caused by incorrect `ExactSizeIterator` implementations. [#2124](https://github.com/PyO3/pyo3/pull/2124) - Fixed undefined behaviour caused by incorrect `ExactSizeIterator` implementations. [#2124](https://github.com/PyO3/pyo3/pull/2124)
- Add missing FFI definitions `_PyLong_NumBits` and `_PyLong_AsByteArray` on PyPy. [#2146](https://github.com/PyO3/pyo3/pull/2146) - Add missing FFI definitions `_PyLong_NumBits` and `_PyLong_AsByteArray` on PyPy. [#2146](https://github.com/PyO3/pyo3/pull/2146)
- Fix memory leak in implementation of `AsPyPointer` for `Option<T>`. [#2160](https://github.com/PyO3/pyo3/pull/2160)
## [0.15.1] - 2021-11-19 ## [0.15.1] - 2021-11-19

View File

@ -44,7 +44,7 @@ where
#[inline] #[inline]
fn as_ptr(&self) -> *mut ffi::PyObject { fn as_ptr(&self) -> *mut ffi::PyObject {
self.as_ref() self.as_ref()
.map_or_else(std::ptr::null_mut, |t| t.into_ptr()) .map_or_else(std::ptr::null_mut, |t| t.as_ptr())
} }
} }
@ -555,7 +555,7 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::types::{IntoPyDict, PyAny, PyDict, PyList}; use crate::types::{IntoPyDict, PyAny, PyDict, PyList};
use crate::{Python, ToPyObject}; use crate::{AsPyPointer, PyObject, Python, ToPyObject};
use super::PyTryFrom; use super::PyTryFrom;
@ -595,4 +595,21 @@ mod tests {
assert_eq!(list, val); assert_eq!(list, val);
}); });
} }
#[test]
fn test_option_as_ptr() {
Python::with_gil(|py| {
let mut option: Option<PyObject> = None;
assert_eq!(option.as_ptr(), std::ptr::null_mut());
let none = py.None();
option = Some(none.clone());
let ref_cnt = none.get_refcnt(py);
assert_eq!(option.as_ptr(), none.as_ptr());
// Ensure ref count not changed by as_ptr call
assert_eq!(none.get_refcnt(py), ref_cnt);
});
}
} }