A common memory leak __c++ in C + + extended Python

Source: Internet
Author: User
a common memory leak in C/A + + extended python

For example, code like this:

Pyobject *dic = Pydict_new ();
Iret = Pydict_setitem (dic, Py_buildvalue ("s", "xxxxxx"), Py_buildvalue ("s"), "Hello xxxx");

This will cause a memory leak.

The correct writing should be this:

Pyobject *dic = Pydict_new ();
Pyobject *obj1 = Py_buildvalue ("s", "xxxxxx");
Pyobject *obj2 = Py_buildvalue ("s", "Hello xxxx");
Iret = Pydict_setitem (dic, Obj1, obj2);
Py_xdecref (obj1);
Py_xdecref (OBJ2);

There is also a way of writing that will lead to Coredump

Pyobject *dic = Pydict_new ();
Pyobject *obj1 = Py_buildvalue ("s", "xxxxxx");
Pyobject *obj2 = Py_buildvalue ("s", "Hello xxxx");
Py_xdecref (obj1);
Py_xdecref (OBJ2);
Iret = Pydict_setitem (dic, Obj1, OBJ2);

In fact, think of the right behavior: Python obj controls the lifecycle through reference. Returns if some obj reference count of c/++ APIs is not 0 at a time. These objects will always be inside the Python virtual machine. Python virtual machines should not have recycled them.

The last situation is a better understanding, access to an already recycled address of course it will coredump slightly

By the way, test methods: 1. Test memory leak is to increase the return data, for multiple calls. Top See the memory is constantly increasing is the memory leak. Long run, overlay test can discover this problem.

Author: Zhihuihui <camel_flying@163.com>

date:2012-06-29 00:02:19 CST

HTML generated by Org-mode 6.33x in Emacs 23

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.