[SciPy-user] numpy array in ctype struct

Ryan May rmay@ou....
Wed Jan 23 08:44:55 CST 2008

Rob Hetland wrote:
> On Jan 22, 2008, at 9:04 PM, Travis E. Oliphant wrote:
>>> Are there any pitfalls to this approach?  It seems to work perfectly
>>> for the test cases I have done.
>> Some minor ones:
>> 1) you have to remember to free the malloc'd pointers.
> This seems to be a problem with my code (below).  Or, more likely, my  
> lack of skill with C.
> I checked it out, and indeed there is a memory leak, that I suspect  
> is related to the pointer array not being freed.  When I try to free  
> the **double array, it seems to also remove the original numpy array  
> that was passed with *pts1.  I tried de-referencing the pointer  
> first, but that also fails.
> What is the best way to release the temporary **double pointers  
> without releasing the associated memory?
> -Rob
> extern "C" void* init_kd_tree(double *pts1, int nPts, int dim) {
>      int i;
>      double **pts;
>      ANNkd_tree *kdTree;
>      /// Convert (*double) input array into a **double
>      pts = (double **)malloc(nPts * sizeof(double *));
>      for (i=0; i<nPts; i++) {
>              pts[i] = pts1 + i*dim;
>      }
>      /// Initialize and return new kd_tree object.
>      kdTree = new ANNkd_tree(pts, nPts, dim);
>      for (i=0; i<nPts; i++) {
>          *pts[i] = NULL;
>      }

I may be grokking this incorrectly, but I think your problem lies here.
 I'm not sure what you're trying to accomplish with this loop (since
setting to NULL isn't necessary before free-ing).  What it actually does
is set the value at the memory address located at pts[i] to NULL (0).
This will end up modifying the values in pts1 itself. (Since pts[i] =
pts1 + i*dim, then *pts[i] is the same as pts1[i*dim].)

>      free(pts);   /// this seems to also delete the input data (pts1)  
> in python..

I'm not sure this is really the case.  It looks like a perfect match for
the malloc above.

>      return kdTree;
> }
> /// below other methods that deal with the object.

If that loop isn't causing the problem, then the problem likely lies


Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma

More information about the SciPy-user mailing list