From 60a3d85b888c70330b7f9e691d8e82d66561d0f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Foucault?= Date: Fri, 12 Apr 2024 17:52:27 +0200 Subject: [PATCH] MEM: Make `MEM_cnew` return aligned memory Now made it so that `MEM_cnew()` can be used for types with any alignment. Fixes #120407. Pull Request: https://projects.blender.org/blender/blender/pulls/120569 --- intern/guardedalloc/MEM_guardedalloc.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/intern/guardedalloc/MEM_guardedalloc.h b/intern/guardedalloc/MEM_guardedalloc.h index 02011da11cb..d5efc16b4ea 100644 --- a/intern/guardedalloc/MEM_guardedalloc.h +++ b/intern/guardedalloc/MEM_guardedalloc.h @@ -38,6 +38,8 @@ #include "../../source/blender/blenlib/BLI_compiler_attrs.h" #include "../../source/blender/blenlib/BLI_sys_types.h" +#include + #ifdef __cplusplus extern "C" { #endif @@ -309,7 +311,16 @@ template inline void MEM_delete(const T *ptr) template inline T *MEM_cnew(const char *allocation_name) { static_assert(std::is_trivial_v, "For non-trivial types, MEM_new should be used."); - return static_cast(MEM_callocN(sizeof(T), allocation_name)); + if (alignof(T) <= MEM_MIN_CPP_ALIGNMENT) { + /* TODO: Could possibly cover more cases, like alignment of 8 or 16. Need to be careful as the + * alignment of MEM_callocN is not really guaranteed. */ + return static_cast(MEM_callocN(sizeof(T), allocation_name)); + } + void *ptr = MEM_mallocN_aligned(sizeof(T), alignof(T), allocation_name); + if (ptr) { + memset(ptr, 0, sizeof(T)); + } + return static_cast(ptr); } /**