Re: [Qemu-devel] [PATCH] Introduce QEMU_NEW()

Richard W.M. Jones
2011-08-01T10:49:38Z

On Mon, Jul 25, 2011 at 11:51:12AM +0300, Avi Kivity wrote:
> qemu_malloc() is type-unsafe as it returns a void pointer. Introduce
> QEMU_NEW() (and QEMU_NEWZ()), which return the correct type.
>
> Signed-off-by: Avi Kivity <avi@redhat.com>
> ---
>
> This is part of my memory API patchset, but doesn't really belong there.
>
> qemu-common.h | 3 +++
> 1 files changed, 3 insertions(+), 0 deletions(-)
>
> diff --git a/qemu-common.h b/qemu-common.h
> index ba55719..66effa3 100644
> --- a/qemu-common.h
> +++ b/qemu-common.h
> @@ -186,6 +186,9 @@ void qemu_free(void *ptr);
> char *qemu_strdup(const char *str);
> char *qemu_strndup(const char *str, size_t size);
>
> +#define QEMU_NEW(type) ((type *)(qemu_malloc(sizeof(type))))
> +#define QEMU_NEWZ(type) ((type *)(qemu_mallocz(sizeof(type))))
> +
> void qemu_mutex_lock_iothread(void);
> void qemu_mutex_unlock_iothread(void);

FYI libvirt have been doing something similar, perhaps even more
far-reaching:

http://libvirt.org/hacking.html#memalloc

http://libvirt.org/git/?p=libvirt.git;a=blob;f=src/util/memory.h;hb=HEAD

The libvirt versions are designed to catch errors in situations such
as:

- trying to allocate zero-sized objects when the underlying malloc
returns NULL for zero-sized objects

- trying to allocate N * M-sized objects when N * M overflows

- realloc fails, don't forget the original pointer

Rich.

--
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
virt-df lists disk usage of guests without needing to install any
software inside the virtual machine. Supports Linux and Windows.