Merge pull request #662 from Aaron1011/fix/final-offset

Don't call 'offset' on a dangling pointer
This commit is contained in:
Sébastien Crozet 2019-11-21 22:11:56 +01:00 committed by GitHub
commit 4e3fb80b4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 3 deletions

View File

@ -27,12 +27,30 @@ macro_rules! iterator {
let shape = storage.shape(); let shape = storage.shape();
let strides = storage.strides(); let strides = storage.strides();
let inner_offset = shape.0.value() * strides.0.value(); let inner_offset = shape.0.value() * strides.0.value();
let size = shape.0.value() * shape.1.value();
let ptr = storage.$ptr(); let ptr = storage.$ptr();
// If we have a size of 0, 'ptr' must be
// dangling. Howver, 'inner_offset' might
// not be zero if only one dimension is zero, so
// we don't want to call 'offset'.
// This pointer will never actually get used
// if our size is '0', so it's fine to use
// 'ptr' for both the start and end.
let inner_end = if size == 0 {
ptr
} else {
// Safety:
// If 'size' is non-zero, we know that 'ptr'
// is not dangling, and 'inner_offset' must lie
// within the allocation
unsafe { ptr.offset(inner_offset as isize) }
};
$Name { $Name {
ptr: ptr, ptr: ptr,
inner_ptr: ptr, inner_ptr: ptr,
inner_end: unsafe { ptr.offset(inner_offset as isize) }, inner_end,
size: shape.0.value() * shape.1.value(), size: shape.0.value() * shape.1.value(),
strides: strides, strides: strides,
_phantoms: PhantomData, _phantoms: PhantomData,

View File

@ -72,7 +72,7 @@ pub unsafe trait Storage<N: Scalar, R: Dim, C: Dim = U1>: Debug + Sized {
/// Gets the address of the i-th matrix component without performing bound-checking. /// Gets the address of the i-th matrix component without performing bound-checking.
#[inline] #[inline]
unsafe fn get_address_unchecked_linear(&self, i: usize) -> *const N { unsafe fn get_address_unchecked_linear(&self, i: usize) -> *const N {
self.ptr().offset(i as isize) self.ptr().wrapping_offset(i as isize)
} }
/// Gets the address of the i-th matrix component without performing bound-checking. /// Gets the address of the i-th matrix component without performing bound-checking.
@ -124,7 +124,7 @@ pub unsafe trait StorageMut<N: Scalar, R: Dim, C: Dim = U1>: Storage<N, R, C> {
/// Gets the mutable address of the i-th matrix component without performing bound-checking. /// Gets the mutable address of the i-th matrix component without performing bound-checking.
#[inline] #[inline]
unsafe fn get_address_unchecked_linear_mut(&mut self, i: usize) -> *mut N { unsafe fn get_address_unchecked_linear_mut(&mut self, i: usize) -> *mut N {
self.ptr_mut().offset(i as isize) self.ptr_mut().wrapping_offset(i as isize)
} }
/// Gets the mutable address of the i-th matrix component without performing bound-checking. /// Gets the mutable address of the i-th matrix component without performing bound-checking.