1 | use super::*; |
2 | |
3 | /// Allocate memory of size `bytes` using `HeapAlloc`. |
4 | /// |
5 | /// The memory allocated by this function is uninitialized. |
6 | /// |
7 | /// This function will fail in OOM situations, if the heap is otherwise corrupt, |
8 | /// or if getting a handle to the process heap fails. |
9 | pub fn heap_alloc(bytes: usize) -> crate::Result<*mut std::ffi::c_void> { |
10 | let ptr: *mut c_void = unsafe { HeapAlloc(hheap:GetProcessHeap(), dwflags:0, dwbytes:bytes) }; |
11 | |
12 | if ptr.is_null() { |
13 | Err(E_OUTOFMEMORY.into()) |
14 | } else { |
15 | // HeapAlloc is not guaranteed to return zero memory but usually does. This just ensures that |
16 | // it predictably returns non-zero memory for testing purposes. This is similar to what MSVC's |
17 | // debug allocator does for the same reason. |
18 | #[cfg (debug_assertions)] |
19 | unsafe { |
20 | std::ptr::write_bytes(dst:ptr, val:0xCC, count:bytes); |
21 | } |
22 | Ok(ptr) |
23 | } |
24 | } |
25 | |
26 | /// Free memory allocated by `HeapAlloc` or `HeapReAlloc`. |
27 | /// |
28 | /// The pointer is allowed to be null. |
29 | /// |
30 | /// # Safety |
31 | /// |
32 | /// `ptr` must be a valid pointer to memory allocated by `HeapAlloc` or `HeapReAlloc` |
33 | pub unsafe fn heap_free(ptr: *mut std::ffi::c_void) { |
34 | HeapFree(hheap:GetProcessHeap(), dwflags:0, lpmem:ptr); |
35 | } |
36 | |