Skip to content

Use malloc on non-Windows platforms #3095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions crates/libs/core/src/imp/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@ use core::ffi::c_void;
/// This function will fail in OOM situations, if the heap is otherwise corrupt,
/// or if getting a handle to the process heap fails.
pub fn heap_alloc(bytes: usize) -> crate::Result<*mut c_void> {
let ptr = unsafe { HeapAlloc(GetProcessHeap(), 0, bytes) };
#[cfg(windows)]
let ptr: *mut c_void = unsafe { HeapAlloc(GetProcessHeap(), 0, bytes) };

#[cfg(not(windows))]
let ptr: *mut c_void = unsafe {
extern "C" {
fn malloc(bytes: usize) -> *mut c_void;
}

malloc(bytes)
};

if ptr.is_null() {
Err(E_OUTOFMEMORY.into())
Expand All @@ -32,5 +42,17 @@ pub fn heap_alloc(bytes: usize) -> crate::Result<*mut c_void> {
///
/// `ptr` must be a valid pointer to memory allocated by `HeapAlloc` or `HeapReAlloc`
pub unsafe fn heap_free(ptr: *mut c_void) {
HeapFree(GetProcessHeap(), 0, ptr);
#[cfg(windows)]
{
HeapFree(GetProcessHeap(), 0, ptr);
}

#[cfg(not(windows))]
{
extern "C" {
fn free(ptr: *mut c_void);
}

free(ptr);
}
}