3

c doesn't do bounds check. So how does cython do the check if it compiles to c?

%%cython --annotate
cimport cython
@cython.boundscheck(True)
cpdef myf():
    cdef double pd[8]
    for i in range(100):
        pd[i] = 0
        print pd[i]

The above code compiles to the same C code no matter whether I set True or False for boundscheck. And if I run myf() there is no warnings (it happens to not crash...).

Update

So cython doens't do bounds check on c arrays anyway.

colinfang
  • 20,909
  • 19
  • 90
  • 173
  • Note: there exist malloc tools for c/c++ (replacing the system libraries' malloc/new) that ensure that out of bound accesses will generate a segfault, such as DUMA or Electric Fence. These tools come with a performance overhead, but could be what you are looking for in your tests. – Florian Castellane Mar 14 '18 at 14:50

1 Answers1

4

http://docs.cython.org/src/reference/compilation.html#compiler-directives

"Cython is free to assume that indexing operations ([]-operator) in the code will not cause any IndexErrors to be raised. Lists, tuples, and strings are affected..."

I think in your code a C double array doesn't store its length anywhere, and so it's impossible for Cython to do any useful checks (except in your very trivial example). However, a built in Python type which can raise IndexErrors should be different (I'd assume numpy arrays, python arrays and cython memoryviews should also be affected since they all have a mechanism for Cython to tell if it's gone off the end).

DavidW
  • 29,336
  • 6
  • 55
  • 86
  • I have a [Cython post](http://stackoverflow.com/questions/41944883/verifying-compatibility-in-compiling-extension-types-and-using-them-with-cdef) you may be able to provide insight on. – ballade4op52 Jan 31 '17 at 20:45