Browse Source

HACKING: document preference for g_new instead of g_malloc

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

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>
tags/v3.0.0-rc0
Murilo Opsfelder Araujo 1 year ago
parent
commit
f7c922ed3d
1 changed files with 9 additions and 0 deletions
  1. 9
    0
      HACKING

+ 9
- 0
HACKING View File

@@ -118,6 +118,15 @@ Please note that g_malloc will exit on allocation failure, so there
118 118
 is no need to test for failure (as you would have to with malloc).
119 119
 Calling g_malloc with a zero size is valid and will return NULL.
120 120
 
121
+Prefer g_new(T, n) instead of g_malloc(sizeof(T) * n) for the following
122
+reasons:
123
+
124
+  a. It catches multiplication overflowing size_t;
125
+  b. It returns T * instead of void *, letting compiler catch more type
126
+     errors.
127
+
128
+Declarations like T *v = g_malloc(sizeof(*v)) are acceptable, though.
129
+
121 130
 Memory allocated by qemu_memalign or qemu_blockalign must be freed with
122 131
 qemu_vfree, since breaking this will cause problems on Win32.
123 132
 

Loading…
Cancel
Save