[SciPy-user] numpy array in ctype struct

Rob Hetland hetland@tamu....
Wed Jan 23 06:59:13 CST 2008

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?


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;

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

     return kdTree;

/// below other methods that deal with the object.

Rob Hetland, Associate Professor
Dept. of Oceanography, Texas A&M University
phone: 979-458-0096, fax: 979-845-6331

More information about the SciPy-user mailing list