0

This is my code for Python Wrapper for C function doing some simple calculation with Rotation matrix and Vectors. My function is transform_object, but it's not causing the problem (I was debuging it also without executing this func).

static PyObject* method_transform(PyObject* self, PyObject* args) {
    double or1, or2, or3;
    double cd1, cd2, cd3;
    double ang1, ang2, ang3;

    if (!PyArg_ParseTuple(args, "(ddd)(ddd)(ddd)", &or1, &or2, &or3, &cd1, &cd2, &cd3, &ang1, &ang2, &ang3)) {
        return NULL;
    }
    double or[3] = { or1, or2, or3 };
    double cd[3] = { cd1, cd2, cd3 };
    double ang[3] = { ang1, ang2, ang3 };
    double* vector = transform_object(or , cd, ang);

    PyObject* list = PyList_New(0);
    int len = 3;

    for (int i = 0; i < len; i++) {
        PyObject* the_object = PyFloat_FromDouble(vector[i]);
        PyList_Append(list, the_object);
    }
    return list;
}

And I have a problem with memory leak, I supose. It's going to infinity.

enter image description here

I tried to commenting line by line and found that problem is in this line:

  PyObject* the_object = PyFloat_FromDouble(vector[i]);

If I repleace vector[i] with for eg. or1 it's the same problem. But I don't know why, there are any limitations to making PyObjects from arrays or something?

rozumir
  • 845
  • 9
  • 20
  • My guess: your not dropping a reference count before returning so the objects are lying in tge heap forever, but where is that is the big question – geckos Sep 17 '20 at 10:36
  • 1
    Try to decref the_object reference count after pushing it to the array – geckos Sep 17 '20 at 10:41
  • 1
    You are right. `Py_DECREF(the_object);` after adding obj to list solve the problem. Thanks! – rozumir Sep 17 '20 at 10:48
  • 1
    Doesn't look like you're freeing `vector` either (if it's allocated by `transform_object()`). – AKX Sep 17 '20 at 10:57

1 Answers1

2

The problem is that you're creating a new object (this set it refcount to 1), appending it to a list and returning the list, this set refcount to 2

When that list goes out of scope it's collected by GC, and floats refcount drop to 1, but now there is no access to it but refcount is still not 0 so they live in the heap forever, so you have your memory leak.

As I said, just drop the refcount of the floats after appending to the list

geckos
  • 5,687
  • 1
  • 41
  • 53