Skip to content

Commit c01eea0

Browse files
committed
Use posix_memalign instead of memalign
Fixes tensorflow#4
1 parent 7354a61 commit c01eea0

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/buffer.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
use libc;
44
use std::borrow::Borrow;
55
use std::borrow::BorrowMut;
6+
use std::cmp;
7+
use std::ffi::CStr;
68
use std::mem;
79
use std::ops::Deref;
810
use std::ops::DerefMut;
@@ -12,6 +14,7 @@ use std::ops::Range;
1214
use std::ops::RangeFrom;
1315
use std::ops::RangeFull;
1416
use std::ops::RangeTo;
17+
use std::ptr;
1518
use std::slice;
1619

1720
/// Fixed-length heap-allocated vector.
@@ -48,14 +51,18 @@ impl<T> Buffer<T> {
4851
pub unsafe fn new_uninitialized(len: usize) -> Self {
4952
let elem_size = mem::size_of::<T>();
5053
let alloc_size = len * elem_size;
51-
let align = mem::align_of::<T>();
54+
let align = cmp::max(mem::align_of::<T>(), mem::size_of::<*const libc::c_void>());
55+
// posix_memalign requires the alignment to be at least sizeof(void*).
5256
// TODO: Use alloc::heap::allocate once it's stable, or at least libc::aligned_alloc once it exists
53-
let ptr = libc::memalign(align, alloc_size) as *mut T;
54-
if ptr.is_null() {
55-
panic!("Failed to allocate. Out of memory?");
57+
let mut ptr = ptr::null::<libc::c_void>() as *mut libc::c_void;
58+
let err = libc::posix_memalign(&mut ptr, align, alloc_size);
59+
if err != 0 {
60+
let c_msg = libc::strerror(err);
61+
let msg = CStr::from_ptr(c_msg);
62+
panic!("Failed to allocate: {}", msg.to_str().unwrap());
5663
}
5764
Buffer {
58-
ptr: ptr,
65+
ptr: ptr as *mut T,
5966
length: len,
6067
owned: true,
6168
}

0 commit comments

Comments
 (0)