C Wrapper Function, crashing Python?

Antoon Pardon apardon at forel.vub.ac.be
Wed Oct 12 15:14:35 CEST 2005


Op 2005-10-12, Java and Swing schreef <codecraig at gmail.com>:
> static PyObject *wrap_doStuff(PyObject *self, PyObject *args) {
> 	// this will store the result in a Python object
> 	PyObject *finalResult;
>
> 	// get arguments from Python
> 	char *result = 0;
> 	char *in= 0;
>     	char *aString = 0;
> 	char *bString = 0;
> 	MY_NUM *a;
> 	MY_NUM *b;
> 	int ok = PyArg_ParseTuple(args, "sss", &in, &aString, &bString);
> 	if (!ok) return 0;
>
> 	// do work to get a and b
> 	// count - returns an int;  GetVal - returns a char *
> 	a = GetVal(aString, count(aString, ","));
> 	b = GetVal(bString, count(bString, ","));
>
> 	// make function call, which returns a char *
> 	result = doStuff(in, a, b);
>
> 	// save result in Python string
> 	finalResult = PyString_FromString(result);
>
> 	// free memory
> 	PyMem_Free(result);
> 	PyMem_Free(a);
> 	PyMem_Free(b);
>
> 	// return the result as a Python string
> 	return finalResult;
> }
>
> ...from python I can call this function 4 times...works fine.  WHen I
> call it for the fifth time python.exe crashes.  im thinking some memory
> problem in the wrapper function perhaps...but I am not sure.  The
> actually C function, doStuff can be called 5, 6,7...N times without a
> problem
> so i know its gotta be my wrapper.
>
> Any ideas?  Thanks!

Well assuming your doStuff is a C function that knows nothing of python.
it might be the PyMem_Free(result).
http://docs.python.org/api/memoryInterface.html says the following:

void PyMem_Free(void *p)
    Frees the memory block pointed to by p, which must have been
    returned by a previous call to PyMem_Malloc() or PyMem_Realloc().
    Otherwise, or if PyMem_Free(p) has been called before, undefined
    behavior occurs. If p is NULL, no operation is performed.

But your result wasn't allocated by a PyMem_Malloc, it was returned
to you by a C function.

-- 
Antoon Pardon



More information about the Python-list mailing list