Skip to content

Commit

Permalink
Fix memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
jiaoew1991 committed Oct 12, 2023
1 parent dcfb535 commit 268dad2
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
4 changes: 3 additions & 1 deletion bindings/c/include/opendal.h
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ typedef struct opendal_result_read {
} opendal_result_read;

typedef struct opendal_reader {
struct BlockingReader *ptr;
struct BlockingReader *inner;
} opendal_reader;

/**
Expand Down Expand Up @@ -930,6 +930,8 @@ void opendal_list_entry_free(struct opendal_list_entry *ptr);

intptr_t opendal_reader_read(const struct opendal_reader *self, uint8_t *buf, uintptr_t len);

void opendal_reader_free(struct opendal_reader *ptr);

#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
Expand Down
14 changes: 11 additions & 3 deletions bindings/c/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,13 +412,13 @@ impl opendal_list_entry {

#[repr(C)]
pub struct opendal_reader {
ptr: *mut od::BlockingReader,
inner: *mut od::BlockingReader,
}

impl opendal_reader {
pub(crate) fn new(reader: od::BlockingReader) -> Self {
Self {
ptr: Box::into_raw(Box::new(reader)),
inner: Box::into_raw(Box::new(reader)),
}
}

Expand All @@ -428,10 +428,18 @@ impl opendal_reader {
panic!("The buffer given is pointing at NULL");
}
let buf = unsafe { std::slice::from_raw_parts_mut(buf, len) };
let r = (*self.ptr).read(buf);
let r = (*self.inner).read(buf);
match r {
Ok(n) => n as isize,
Err(_) => -1,
}
}

#[no_mangle]
pub unsafe extern "C" fn opendal_reader_free(ptr: *mut opendal_reader) {
if !ptr.is_null() {
let _ = unsafe { Box::from_raw((*ptr).inner) };
let _ = unsafe { Box::from_raw(ptr) };
}
}
}
1 change: 1 addition & 0 deletions bindings/c/tests/bdd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ TEST_F(OpendalBddTest, FeatureTest)
for (int i = 0; i < this->content.length(); i++) {
EXPECT_EQ(this->content[i], buffer[i]);
}
opendal_reader_free(reader.reader);

// The blocking file should be deleted
code = opendal_operator_blocking_delete(this->p, this->path.c_str());
Expand Down

0 comments on commit 268dad2

Please sign in to comment.