[Numpy-discussion] Re: Freeing memory allocated in C

Robert Kern robert.kern at gmail.com
Thu Apr 27 21:14:02 CDT 2006


Nick Fotopoulos wrote:
> Dear numpy-discussion,
> 
> I have written a python module in C which wraps a C library (FrameL)  in
> order to read data from specially formatted files into Python  arrays. 
> It works, but I think have a memory leak, and I can't see  what I might
> be doing wrong.  This Python wrapper is almost identical  to a Matlab
> wrapper, but the Matlab version doesn't leak.  Perhaps  someone here can
> help me out?
> 
> I have read in many places that to return an array, one should wrap 
> with PyArray_FromDimsAndData (or more modern versions) and then  return
> it without freeing the memory.  Does the same principle hold  for
> strings?  Are the following example snippets correct?
> 
> // output2 = x-axis values relative to first data point.
> data = malloc(nData*sizeof(double));
> for(i=0; i<nData; i++) {
>   data[i] = vect->startX[0]+(double)i*dt;
> }
> shape[0] = nData;
> out2 = (PyArrayObject *)
>         PyArray_FromDimsAndData(1,shape,PyArray_DOUBLE,(char *)data);

I wouldn't rely on PyArray_FromDimsAndData doing the right thing. Instead of
malloc'ing a block of memory, why don't you create an empty array of the right
size, use its data pointer to fill it with that for-loop, and then return that
array object?

> //snip
> 
> // output5 = gps start time as a string
> utc = vect->GTime - vect->ULeapS + FRGPSTAI;
> out5 = malloc(200*sizeof(char));
> sprintf(out5,"Starting GPS time:%.1f UTC=%s",
>     vect->GTime,FrStrGTime(utc));
> 
> //snip -- Free all memory not assigned to a return object
> 
> return Py_BuildValue("(OOOdsss)",out1,out2,out3,out4,out5,out6,out7);
> 
> I see in the Numpy book that I should modernize 
> PyArray_FromDimsAndData, but will it be incompatible with users who 
> have only Numeric?

Yes. However, I would suggest that new code should probably use just use numpy
fully especially if the restrictions of the old Numeric API is causing you pain.
The longer people support both, the longer people will *have* to support both.

-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco





More information about the Numpy-discussion mailing list