[Bf-blender-cvs] [6f511f67225] functions: Fix raw allocator

Jacques Lucke noreply at git.blender.org
Wed Aug 21 14:44:17 CEST 2019


Commit: 6f511f67225ff0745b2cf8580a938b23d9148c4e
Author: Jacques Lucke
Date:   Wed Aug 21 14:44:09 2019 +0200
Branches: functions
https://developer.blender.org/rB6f511f67225ff0745b2cf8580a938b23d9148c4e

Fix raw allocator

This allocator is necessary because sometimes we don't want to use
Blenders guarded allocator. Especially when an object lives longer
than the guarded allocator.

===================================================================

M	source/blender/blenlib/BLI_allocator.hpp

===================================================================

diff --git a/source/blender/blenlib/BLI_allocator.hpp b/source/blender/blenlib/BLI_allocator.hpp
index 89378ff2c40..4da905e9e63 100644
--- a/source/blender/blenlib/BLI_allocator.hpp
+++ b/source/blender/blenlib/BLI_allocator.hpp
@@ -5,6 +5,7 @@
 #include "MEM_guardedalloc.h"
 
 #include "BLI_utildefines.h"
+#include "BLI_math_base.h"
 #include "BLI_temporary_allocator.h"
 
 namespace BLI {
@@ -29,20 +30,37 @@ class GuardedAllocator {
 };
 
 class RawAllocator {
+ private:
+  struct MemHead {
+    int offset;
+  };
+
  public:
   void *allocate(uint size, const char *UNUSED(name))
   {
-    return malloc(size);
+    void *ptr = malloc(size + sizeof(MemHead));
+    ((MemHead *)ptr)->offset = sizeof(MemHead);
+    return POINTER_OFFSET(ptr, sizeof(MemHead));
   }
 
   void *allocate_aligned(uint size, uint alignment, const char *UNUSED(name))
   {
-    return aligned_alloc(alignment, size);
+    BLI_assert(is_power_of_2_i(alignment));
+    void *ptr = malloc(size + alignment + sizeof(MemHead));
+    void *used_ptr = (void *)((uintptr_t)POINTER_OFFSET(ptr, alignment + sizeof(MemHead)) &
+                              ~((uintptr_t)alignment - 1));
+    uint offset = (uintptr_t)used_ptr - (uintptr_t)ptr;
+    BLI_assert(offset >= sizeof(MemHead));
+    ((MemHead *)used_ptr - 1)->offset = offset;
+    return used_ptr;
   }
 
   void deallocate(void *ptr)
   {
-    free(ptr);
+    MemHead *head = (MemHead *)ptr - 1;
+    int offset = -head->offset;
+    void *actual_pointer = POINTER_OFFSET(ptr, offset);
+    free(actual_pointer);
   }
 };



More information about the Bf-blender-cvs mailing list