Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension?

前端 未结 2 1976
囚心锁ツ
囚心锁ツ 2021-01-05 06:36

Whenever I called my function, memory usage is increased around +10M per call, so I think there is some memory leak here.

....
PyObject *pair = PyTuple_New(2         


        
2条回答
  •  我在风中等你
    2021-01-05 06:48

    When an object is created, its refcount will be 1, so after this:

    my_item  = PyInt_FromLong(jp)
    

    the object at my_item will have a refcount of 1.

    When you store an item into a container, the item's reference count is incremented so that the item will be retained, so after this:

    PyList_Append(my_list, my_item);
    

    the object at my_item will have a refcount of 2.

    Therefore, this line:

    PyList_Append(item, PyInt_FromLong(jp));
    

    will create an object with refcount 1 and store it in the list, incrementing the object's refcount to 2.

提交回复
热议问题