1

Here's an example:

%load_ext cython

%%cython -a

from libc.stdlib cimport malloc

def main():
    cdef int *qux = <int*>malloc(3*sizeof(int))
    qux[0] = 4
    qux[1] = 5
    qux[2] = 6
    qux[3] = 7
    print(qux[0])
    print(qux[3])

I was expecting the first print statement to work, but for either qux[3] = 7 to fail, or print(qux[3]) to print garbage. However, it correctly prints 7.

Why is this? Does it not matter how much I malloc to qux?

ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65
  • Using Cython exposes you to all the quirks of C, including undefined behavior. Memory access in C via pointers (or array indices, which are equivalent) is not safeguarded. – Karl Knechtel Jun 22 '22 at 19:02
  • @KarlKnechtel OK, so it _happens_ to have printed the correct result here, but there's no guarantee of that? Thanks – ignoring_gravity Jun 22 '22 at 20:50

0 Answers0