Skip to content

Commit

Permalink
Merge pull request #42 from cupy/avoid-invalid-pointer-arithmetic
Browse files Browse the repository at this point in the history
Avoid adding non-zero offset to zero-pointer
  • Loading branch information
okuta committed May 23, 2017
2 parents 8d7546c + bf1fe44 commit bd2e0d7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
13 changes: 10 additions & 3 deletions cupy/core/core.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1222,10 +1222,16 @@ cdef class ndarray:
else:
dim = (s_stop - s_start + 1) // s_step + 1

if dim == 0:
strides.push_back(self._strides[j])
else:
strides.push_back(self._strides[j] * s_step)

if self.size > 0:
offset += self._strides[j] * max(0, s_start)

shape.push_back(dim)
strides.push_back(self._strides[j] * s_step)

offset += max(0, s_start) * self._strides[j]
j += 1
elif numpy.isscalar(s):
ind = int(s)
Expand All @@ -1235,7 +1241,8 @@ cdef class ndarray:
msg = ('Index %s is out of bounds for axis %s with '
'size %s' % (s, j, self._shape[j]))
raise IndexError(msg)
offset += ind * self._strides[j]
if self.size > 0:
offset += ind * self._strides[j]
j += 1
else:
raise TypeError('Invalid index type: %s' % type(slices[i]))
Expand Down
3 changes: 3 additions & 0 deletions cupy/cuda/memory.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ cdef class MemoryPointer:
"""

def __init__(self, mem, Py_ssize_t offset):
assert mem.ptr > 0 or offset == 0
self.mem = mem
self.device = mem.device
self.ptr = mem.ptr + offset
Expand All @@ -101,11 +102,13 @@ cdef class MemoryPointer:
else:
self = <MemoryPointer?>y
offset = <Py_ssize_t?>x
assert self.ptr > 0 or offset == 0
return MemoryPointer(self.mem,
self.ptr - self.mem.ptr + offset)

def __iadd__(self, Py_ssize_t offset):
"""Adds an offset to the pointer in place."""
assert self.ptr > 0 or offset == 0
self.ptr += offset
return self

Expand Down
3 changes: 3 additions & 0 deletions tests/cupy_tests/core_tests/test_ndarray_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@
'indexes': (None, slice(None, None, -1))},
{'shape': (1, 0, 1), 'transpose': None,
'indexes': (None, slice(None, None, -1), None)},
#
{'shape': (2, 0), 'transpose': None,
'indexes': (1, slice(None, None, None))},
)
@testing.gpu
class TestArrayIndexingParameterized(unittest.TestCase):
Expand Down

0 comments on commit bd2e0d7

Please sign in to comment.