Skip to content

Commit f3b1162

Browse files
committed
fix memory overallocation
1 parent 845f6f7 commit f3b1162

1 file changed

Lines changed: 10 additions & 14 deletions

File tree

crates/kcserver/src/process_tree.rs

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -93,28 +93,24 @@ mod macos {
9393

9494
/// Get child PIDs of a process using proc_listchildpids()
9595
fn get_child_pids(pid: u32) -> Vec<u32> {
96-
// First call with null buffer to get the count
96+
// First call with null buffer to get the required buffer size in bytes
9797
// SAFETY: proc_listchildpids is a well-documented macOS API that safely handles
98-
// null buffer pointers by returning the required buffer size.
99-
let count = unsafe { proc_listchildpids(pid as libc::c_int, std::ptr::null_mut(), 0) };
98+
// null buffer pointers by returning the required buffer size in bytes.
99+
let bytes_needed =
100+
unsafe { proc_listchildpids(pid as libc::c_int, std::ptr::null_mut(), 0) };
100101

101-
if count <= 0 {
102+
if bytes_needed <= 0 {
102103
return Vec::new();
103104
}
104105

105-
// Allocate buffer for PIDs
106-
let buffer_size = count as usize;
107-
let mut buffer: Vec<libc::c_int> = vec![0; buffer_size];
106+
// Allocate buffer for PIDs (convert bytes to element count)
107+
let count = bytes_needed as usize / size_of::<libc::c_int>();
108+
let mut buffer: Vec<libc::c_int> = vec![0; count];
108109

109110
// SAFETY: We've allocated a buffer of sufficient size (as returned by the first call).
110111
// proc_listchildpids writes at most buffersize bytes to the buffer.
111-
let result = unsafe {
112-
proc_listchildpids(
113-
pid as libc::c_int,
114-
buffer.as_mut_ptr(),
115-
(buffer_size * size_of::<libc::c_int>()) as libc::c_int,
116-
)
117-
};
112+
let result =
113+
unsafe { proc_listchildpids(pid as libc::c_int, buffer.as_mut_ptr(), bytes_needed) };
118114

119115
if result <= 0 {
120116
return Vec::new();

0 commit comments

Comments
 (0)