[SciPy-User] Stack corruption in extension module.

J. David Lee johnl@cs.wisc....
Wed Jan 25 23:46:34 CST 2012


Hi,

Sorry that this is a bit off-topic, but I'm having an interesting 
problem with a C extension module. Here is a simple test module, 
stack_test.c:

#define PY_ARRAY_UNIQUE_SYMBOL __np_inline_stack_test
#include<Python.h>
#include<numpy/arrayobject.h>
#include<math.h>

// Forward declarations of our function.
static PyObject *function(PyObject *self, PyObject *args);


// Boilerplate: function list.
static PyMethodDef methods[] = {
     { "function", function, METH_VARARGS, "Doc string."},
     { NULL, NULL, 0, NULL } /* Sentinel */
};

// Boilerplate: Module initialization.
PyMODINIT_FUNC initstack_test(void) {
         (void) Py_InitModule("stack_test", methods);
         import_array();
}

static void calc_A(npy_int64 i, npy_int64 P, npy_int64 Q,
             npy_float64 *R, npy_float64 *A , npy_float64 b) {
   printf("Start : i: %li P: %f Q: %f R: %f A: %f b: %f\n", i, P, Q, *R, *A, b);
   *R = 6.0;
   *A = 7.0;
   printf("End   : i: %li P: %f Q: %f R: %f A: %f b: %f\n", i, P, Q, *R, *A, b);
}

static PyObject *function(PyObject *self, PyObject *args) {

   long th;
   long return_val = 34;


   if (!PyArg_ParseTuple(args, "l",&th)) {
     return NULL;
   }

   npy_float64 P=0;
   npy_float64 Q=0;
   npy_float64 R=0;
   npy_float64 A=0;
   npy_float64 b=0;
   npy_int64 i = 0;

   P = 1;
   Q = 2;
   R = 3;
   A = 4;
   b = 5;

   printf("Before: i: %li P: %f Q: %f R: %f A: %f b: %f\n", i, P, Q, R, A, b);
   calc_A(i, P, Q,&R,&A, b);
   printf("After : i: %li P: %f Q: %f R: %f A: %f b: %f\n", i, P, Q, R, A, b);

   return PyLong_FromLong(return_val);

}



I compile with:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -UNDEBUG -I/usr/lib/pymodules/python2.7/numpy/core/include -I/usr/include/python2.7 -c stack_test.c -o stack_test.o
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-function stack_test.o stack_test.so


Now when I run the function:

stack_test.function(1)
Before: i: 0 P: 1.000000 Q: 2.000000 R: 3.000000 A: 4.000000 b: 5.000000
Start : i: 0 P: 3.000000 Q: 4.000000 R: 5.000000 A: 4.000000 b: 5.000000
End   : i: 0 P: 6.000000 Q: 7.000000 R: 5.000000 A: 4.000000 b: 5.000000
After : i: 0 P: 1.000000 Q: 2.000000 R: 6.000000 A: 7.000000 b: 5.000000


which is clearly wrong.

I'm using python 2.7.2 built with gcc 4.6.2.

If you have any suggestions, I'd love to hear them.

Thanks,

David

PS The numpy stuff is in there because this used to be doing some array 
calculations. I cut it down to a minimum that still had bad behavior.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: stack_test.c
Type: text/x-csrc
Size: 1472 bytes
Desc: not available
Url : http://mail.scipy.org/pipermail/scipy-user/attachments/20120125/26f2caae/attachment.bin 


More information about the SciPy-User mailing list