Skip to content

Commit dd7af70

Browse files
committedNov 22, 2018
work with nil returned by malloc for 0-sized arrays
1 parent 84f16fb commit dd7af70

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed
 

‎Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
name = "alloc-no-stdlib"
33
description = "A dynamic allocator that may be used with or without the stdlib. This allows a package with nostd to allocate memory dynamically and be used either with a custom allocator, items on the stack, or by a package that wishes to simply use Box<>. It also provides options to use calloc or a mutable global variable for pre-zeroed memory"
4-
version = "2.0.0"
4+
version = "2.0.1"
55
authors = ["Daniel Reiter Horn <danielrh@dropbox.com>"]
66
documentation = "https://raw.githubusercontent.com/dropbox/rust-alloc-no-stdlib/master/tests/lib.rs"
77
homepage = "https://github.com/dropbox/rust-alloc-no-stdlib"

‎src/lib.rs

+15-6
Original file line numberDiff line numberDiff line change
@@ -39,25 +39,34 @@ pub enum AllocatorC {
3939
}
4040
impl<'a, T : 'a> CallocBackingStore<'a, T> {
4141
pub unsafe fn new(num_elements : usize, alloc : AllocatorC, free : unsafe extern "C" fn (*mut u8), should_free : bool) -> Self{
42-
let retval : *mut u8 = match alloc {
43-
AllocatorC::Calloc(calloc) => calloc(num_elements, core::mem::size_of::<T>()),
44-
AllocatorC::Malloc(malloc) => malloc(num_elements *core::mem::size_of::<T>()),
45-
AllocatorC::Custom(malloc) => malloc(num_elements *core::mem::size_of::<T>()),
42+
let retval : *mut u8 = if num_elements == 0 {core::ptr::null_mut()} else {
43+
match alloc {
44+
AllocatorC::Calloc(calloc) => calloc(num_elements, core::mem::size_of::<T>()),
45+
AllocatorC::Malloc(malloc) => malloc(num_elements *core::mem::size_of::<T>()),
46+
AllocatorC::Custom(malloc) => malloc(num_elements *core::mem::size_of::<T>()),
47+
}
4648
};
49+
if num_elements == 0 || retval.is_null() {
50+
return CallocBackingStore::<'a, T>{
51+
raw_data : core::ptr::null_mut(),
52+
data : &mut[],
53+
free : free,
54+
}
55+
}
4756
let raw_data : *mut T = core::mem::transmute(retval);
4857
if should_free {
4958
return CallocBackingStore::<'a, T>{
5059
raw_data : retval,
5160
data : core::slice::from_raw_parts_mut(raw_data,
52-
num_elements),
61+
num_elements),
5362
free : free,
5463
};
5564
} else {
5665
let null_ptr : *const u8 = core::ptr::null();
5766
return CallocBackingStore::<'a, T>{
5867
raw_data : core::mem::transmute(null_ptr),//retval,
5968
data : core::slice::from_raw_parts_mut(raw_data,
60-
num_elements),
69+
num_elements),
6170
free : free,
6271
};
6372
}

0 commit comments

Comments
 (0)
Please sign in to comment.