[libvirt] [PATCHv2] python: Avoid memory leaks on libvirt_virNodeGetMemoryStats

Eric Blake eblake at redhat.com
Tue Feb 14 13:14:30 UTC 2012


On 02/14/2012 04:19 AM, ajia at redhat.com wrote:
> From: Alex Jia <ajia at redhat.com>
> 
> Detected by valgrind. Leaks are introduced in commit 17c7795.
> 
> * python/libvirt-override.c (libvirt_virNodeGetMemoryStats): fix memory leaks
> and improve codes return value.
> 
> For details, please see the following link:
> RHBZ: https://bugzilla.redhat.com/show_bug.cgi?id=770944
> 
> Signed-off-by: Alex Jia <ajia at redhat.com>
> ---
>  python/libvirt-override.c |   43 +++++++++++++++++++++++++++++--------------
>  1 files changed, 29 insertions(+), 14 deletions(-)
> 
> diff --git a/python/libvirt-override.c b/python/libvirt-override.c
> index 4e8a97e..594aae6 100644
> --- a/python/libvirt-override.c
> +++ b/python/libvirt-override.c
> @@ -2426,7 +2426,9 @@ libvirt_virNodeGetCPUStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)
>  static PyObject *
>  libvirt_virNodeGetMemoryStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)
>  {
> -    PyObject *ret;
> +    PyObject *ret = VIR_PY_NONE;

NAK - this increments the reference count on the None object...

> +    PyObject *key = NULL;
> +    PyObject *val = NULL;
>      PyObject *pyobj_conn;
>      virConnectPtr conn;
>      unsigned int flags;
> @@ -2442,32 +2444,45 @@ libvirt_virNodeGetMemoryStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)
>      c_retval = virNodeGetMemoryStats(conn, cellNum, NULL, &nparams, flags);
>      LIBVIRT_END_ALLOW_THREADS;
>      if (c_retval < 0)
> -        return VIR_PY_NONE;
> +        return ret;
>  
>      if (nparams) {
>          if (VIR_ALLOC_N(stats, nparams) < 0)
> -            return VIR_PY_NONE;
> +            return PyErr_NoMemory();

...but this fails to decrement the reference count, so you've leaked a
resource.  See my comments on v1.

> +
> +        if (PyDict_SetItem(ret, key, val) < 0) {
> +            Py_DECREF(ret);
> +            goto error;

And here, you have a python exception from PyDict_SetItem...

> +        }
> +
> +        Py_DECREF(key);
> +        Py_DECREF(val);
>      }
>  
>      VIR_FREE(stats);
>      return ret;
> +
> +error:
> +    VIR_FREE(stats);
> +    Py_XDECREF(key);
> +    Py_XDECREF(val);
> +    return ret;

...so here, you _want_ to return NULL, not VIR_PY_NONE.

-- 
Eric Blake   eblake at redhat.com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 620 bytes
Desc: OpenPGP digital signature
URL: <http://listman.redhat.com/archives/libvir-list/attachments/20120214/eb6dfdec/attachment-0001.sig>


More information about the libvir-list mailing list