nrn icon indicating copy to clipboard operation
nrn copied to clipboard

Vector.`as_numpy` is unsafe

Open ferdonline opened this issue 2 years ago • 1 comments

Context

Vector.as_numpy is a performant way to expose a Vector's data to Python. However, the Python array does't seem to extend the lifetime of the underlying data and we very easily end up in situations of accessing a freed chunk of memory. Very often we will create a segmentation fault, but most time we will read invalid data.

Overview of the issue

This short example shows the issue.

>>> h.Vector(5, 2).as_numpy()
array([ 4.66582517e-310,  2.47138908e-202,  2.00000000e+000,
        2.00000000e+000,  2.00000000e+000])

The Vector object is freed as the end of the as_numpy, the resulting numpy object, when printed by the interpreter, already contains a dangling pointer to Vector's data.

By doing h.Vector(5, 2).as_numpy()[0]=5 we will likely have a segmentation fault.

Expected result/behavior

The resulting numpy / numpy-like object should reference the Vector so it stays alive. The previous snippet should return

>>> h.Vector(5, 2).as_numpy()
array([2., 2., 2., 2., 2.])

ferdonline avatar Sep 27 '23 14:09 ferdonline

This behaviour is precisely documented :)

1uc avatar Sep 27 '23 14:09 1uc