Skip to content

Commit 9e56f71

Browse files
committed
Fix a memory leak in Buffer.
The Buffer type seems to conflate ownership of the TF_Buffer object and the ownership of the data wrapped by the TF_Buffer object. A TF_Buffer object created through from_ptr() is created as 'borrowed'. As a result, the TF_Buffer object is not deallocated, leadning to a memory leak. This commit makes two small changes to (hopefully) remedy the leak: - from_ptr() sets the TF_Buffer to be owned, so that the drop() will deallocate the TF_Buffer object. Since the TF_Buffer does not have a data_deallocator set, the data is not freed when Buffer is dropped. - into_ptr() does not change the TF_Buffer ownership, but instead sets data_deallocator to NULL. As a consequence, the caller becomes responsible for freeing the data and the TF_Buffer is deallocated by drop().
1 parent 701d5ec commit 9e56f71

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/buffer.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ impl<T: TensorType> Buffer<T> {
8686
(*inner).length = len;
8787
Buffer {
8888
inner: inner,
89-
owned: false,
89+
owned: true,
9090
phantom: PhantomData,
9191
}
9292
}
@@ -96,8 +96,7 @@ impl<T: TensorType> Buffer<T> {
9696
/// The caller is responsible for freeing the data.
9797
pub unsafe fn into_ptr(mut self) -> (*mut T, usize) {
9898
// TODO: remove
99-
// This flag is used by drop.
100-
self.owned = false;
99+
(*self.inner).data_deallocator = None;
101100
(self.data_mut(), self.length())
102101
}
103102

@@ -128,7 +127,8 @@ impl<T: TensorType> Buffer<T> {
128127
/// Creates a buffer from data owned by the C API.
129128
///
130129
/// `len` is the number of elements.
131-
/// The underlying data is freed when the buffer is destroyed if `owned` is true.
130+
/// The underlying data is freed when the buffer is destroyed if `owned`
131+
/// is true and the `buf` has a data deallocator.
132132
pub unsafe fn from_c(buf: *mut tf::TF_Buffer, owned: bool) -> Self {
133133
Buffer {
134134
inner: buf,

0 commit comments

Comments
 (0)