Python C API String Memory Consumption

k3xji sumerc at
Tue Apr 7 09:01:39 CEST 2009

When I run the following function, I seem to have a mem leak, a 20 mb
of memory
is allocated and is not freed. Here is the code I run:

>>> import esauth
>>> for i in range(1000000):

...     ss = esauth.penc('sumer')
>>> for i in range(1000000):

...     ss = esauth.penc('sumer')

And here is the penc() function.

static PyObject *
penc(PyObject *self, PyObject *args)
        unsigned char *s= NULL;
        unsigned char *buf = NULL;
        PyObject * result = NULL;
        unsigned int v,len,i = 0;

        if (!PyArg_ParseTuple(args, "s#", &s, &len))
        return NULL;

        buf = strdup(s);
        if (!buf) {
                        "Out of memory: strdup failed");
                return NULL;

        /*string manipulation*/

        result = PyString_FromString(buf);
        return result;


Am I doing something wrong?


More information about the Python-list mailing list