diff mbox series

[PULL,05/22] HACKING: document preference for g_new instead of g_malloc

Message ID f7c922ed3d8e3cb54febbdc594ce9f4400e0d290.1526796813.git.mjt@msgid.tls.msk.ru
State New
Headers show
Series [PULL,01/22] tcg: fix s/compliment/complement/ typos | expand

Commit Message

Michael Tokarev May 20, 2018, 6:14 a.m. UTC
From: Murilo Opsfelder Araujo <muriloo@linux.ibm.com>

This patch documents the preference for g_new instead of g_malloc. The
reasons were adapted from commit b45c03f585ea9bb1af76c73e82195418c294919d.

Discussion in QEMU's mailing list:
  http://lists.nongnu.org/archive/html/qemu-devel/2018-05/msg03238.html

Cc: qemu-devel@nongnu.org
Cc: David Hildenbrand <david@redhat.com>
Cc: Eduardo Habkost <ehabkost@redhat.com>
Cc: Markus Armbruster <armbru@redhat.com>
Cc: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Murilo Opsfelder Araujo <muriloo@linux.ibm.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Alex Bennée <alex.bennee@linaro.org>
Reviewed-by: David Hildenbrand <david@redhat.com>
Signed-off-by: Michael Tokarev <mjt@tls.msk.ru>
---
 HACKING | 9 +++++++++
 1 file changed, 9 insertions(+)
diff mbox series

Patch

diff --git a/HACKING b/HACKING
index 4125c97d8d..0fc3e0fc04 100644
--- a/HACKING
+++ b/HACKING
@@ -118,6 +118,15 @@  Please note that g_malloc will exit on allocation failure, so there
 is no need to test for failure (as you would have to with malloc).
 Calling g_malloc with a zero size is valid and will return NULL.
 
+Prefer g_new(T, n) instead of g_malloc(sizeof(T) * n) for the following
+reasons:
+
+  a. It catches multiplication overflowing size_t;
+  b. It returns T * instead of void *, letting compiler catch more type
+     errors.
+
+Declarations like T *v = g_malloc(sizeof(*v)) are acceptable, though.
+
 Memory allocated by qemu_memalign or qemu_blockalign must be freed with
 qemu_vfree, since breaking this will cause problems on Win32.