[Matrix-SIG] Fix for a long-standing NumPy bug

Charles G Waldman cgw@pgt.com
Tue, 22 Dec 1998 17:49:51 -0500 (EST)


Here's a fix for a bug I first reported back in September:

http://www.python.org/pipermail/matrix-sig/1998-September/002337.html

It can be triggered by the following code:

from Numeric import *
a = array((1,2,3,4,5,6,7,8))
a.shape = 2,2,2
x,y = a
x.shape = 4,1


Well,  using the wonderful "MALLOC_CHECK_" feature of recent libc
versions (set environment variable MALLOC_CHECK_ to 1) I was able to
trace this down to a free() of an invalid pointer.  With that
information in hand,  it wasn't too hard to track down the offending
code.  Here's a patch:


--- arrayobject.c.orig  Tue Dec 22 17:34:28 1998
+++ arrayobject.c       Tue Dec 22 17:35:31 1998
@@ -1399,9 +1399,9 @@
        if (strcmp(name, "shape") == 0) {
                /* This can be made more efficient by copying code from array_reshape if needed */
                if ((ap = (PyArrayObject *)PyArray_Reshape(self, op)) == NULL) return -1;
-               free(self->dimensions);
+               if (self->flags & OWN_DIMENSIONS) free(self->dimensions);
                self->dimensions = ap->dimensions;
-               free(self->strides);
+               if (self->flags & OWN_STRIDES) free(self->strides);
                self->strides = ap->strides;
                self->nd = ap->nd;
                self->flags &= ~(OWN_DIMENSIONS | OWN_STRIDES);