tiny extension crashes

John J. Lee phrxy at csv.warwick.ac.uk
Thu Mar 15 19:05:02 EST 2001


On Thu, 15 Mar 2001, Greg Jorgensen wrote:

> You have an uninitialized pointer, intp, in your iround() function. Do this:
[...]

Oops, thanks.

What I still don't get, though, is why it was crashing even when only the
hcf()  function was being imported and called by my (pure) Python code.
Surely if it doesn't get called, the uninitialised pointer can't scribble
over anything?

> Since you posted your source code, let me suggest an alternative
> implementation of array_max:
>
> static long array_max(PyArrayObject *array, int absolute)
> {
>     long *a = array->data;
>     long stride = array->strides[0];
>     long max = 0;
>
>     if (absolute) {
>         for (i = 0; i < array->dimensions[0]; i++) {
>             if (labs(*a) > max)
>                 max = labs(*a);
>             a += stride;
>         }
>     }
>     else {
>         for (i = 0; i < array->dimensions[0]; i++) {
>             if (*a > max)
>                 max = *a;
>             a += stride;
>         }
>     }
>     return max;
> }
>
> The test on absolute only happens once, not at every loop iteration. (I
> would make this two functions, one that works on the actual values and one
> that works on the absolute values.)

Yeah, so would I, but my C is so rusty that I couldn't be bothered with
the effort (not that my knowledge of C was ever clean and shiny).  :)
That's what these interpreted languages do to you -- I'm spoilt.

> The array->data[] index calculation is
> changed to pointer addition. And I used the labs() function rather than the
> unnecessary floating-point fabs() version. And I changed max to a long, and
> made the function return a long.

All good tips, thanks.  (Although as it happens, in this particular case,
I had intended to replace that function with the built-in Numeric max(),
when I had got round to looking up how to call Python functions from C.
In fact I'll probably scrap all of these functions eventually -- they're
only there because they were the simplest functions I had lying around,
and I knew I'd certainly get tangled up in C if I picked something more
complicated for my first extension.)


John




More information about the Python-list mailing list