Skip to content

Commit e23abf6

Browse files
committed
Improve memory usage
Avoid unnecessary allocation of an empty string. Fix a memory leak resulting from not calling CString::from_raw in case of NFD_CANCEL or NFD_ERROR.
1 parent 4258be9 commit e23abf6

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/lib.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,21 +55,22 @@ fn open_dialog(filter_list: Option<&str>, default_path: Option<&str>, dialog_typ
5555
None => std::ptr::null()
5656
};
5757

58-
let out_path = CString::new("").unwrap().into_raw() as *mut *mut c_char;
58+
let mut out_path: *mut c_char = std::ptr::null_mut();
59+
let ptr_out_path = &mut out_path as *mut *mut c_char;
5960

6061
unsafe {
6162
result = match dialog_type {
6263
&DialogType::SingleFile => {
63-
NFD_OpenDialog(filter_list_ptr, default_path_ptr, out_path)
64+
NFD_OpenDialog(filter_list_ptr, default_path_ptr, ptr_out_path)
6465
},
6566

6667
&DialogType::SaveFile => {
67-
NFD_SaveDialog(filter_list_ptr, default_path_ptr, out_path)
68+
NFD_SaveDialog(filter_list_ptr, default_path_ptr, ptr_out_path)
6869
},
6970
};
7071

7172
result_cstring = match result {
72-
nfdresult_t::NFD_OKAY => CString::from_raw(*out_path),
73+
nfdresult_t::NFD_OKAY => CStr::from_ptr(out_path).to_owned(),
7374
nfdresult_t::NFD_ERROR => CStr::from_ptr(NFD_GetError()).to_owned(),
7475
_ => CString::new("").unwrap()
7576
}

0 commit comments

Comments
 (0)