Memory leak

Andrew Gregory andrew.gregory at npl.co.uk
Tue Mar 4 07:07:08 EST 2003


I keep being troubled by memory leaks when using C/C++ extensions (I
have Python 2.2.2 on Windows). The problem is most acute in
mathematical code, in which a C routine in an extension is called
repeatedly in a loop. So I wrote a simple test program:

// test.h
typedef PyObject* RESULTOBJ;

  // Hand-coded wrapper for returning string
  RESULTOBJ wrap_string(char *s)
  {
    RESULTOBJ result;
    result = PyString_FromString(s);
    return Py_BuildValue("O",result);
  };

  
  RESULTOBJ getstring()
  {
    static char *s = "This is a message string";
    RESULTOBJ result = wrap_string(s);
    return result;
  };

// test.i
%module test
%{
   #include "test.h"
%};

%include test.h


which is then wrapped using SWIG 1.3.17 (SWIG -python test.i) and
compiled.

In Python,

>>> import _test
>>> k=0
>>> for i in range(2000):
... 	s=_test.getstring()
... 	k=k+1
... 	if k==200:
... 		k=0
... 		print i, s
... 
199 This is a message string
399 This is a message string
etc.

If I make the number of loops large enough (say 200000) then I get a
crash, just like I do with my mathematical programs. My understanding
is that Python will delete the PyObjects created with
PyString_FromString() automatically. Does anyone have any ideas?

Andrew.




More information about the Python-list mailing list