How to free a malloc'ed char* returned with SWIG

c, python, swig

Solution

Use the `%newobject` directive in your `.i` file. From the SWIG 2.0 documentation:

If you have a function that allocates memory like this,

char *foo() {
   char *result = (char *) malloc(...);
   ...
   return result;
}

then the SWIG generated wrappers will have a memory leak--the returned data will be copied into a string object and the old contents ignored.

To fix the memory leak, use the %newobject directive.

%newobject foo;
...
char *foo();

Problem

I'm using SWIG and my function returns a `char *`, which was malloc'ed. SWIG returns `PyString_FromStringAndSize(my-char-str, len)`. Is there a way to free this `my-char-str` without editing the C wrapper code?

Original source