gemini-code-assist[bot] commented on code in PR #65:
URL: https://github.com/apache/tvm-ffi/pull/65#discussion_r2384317960


##########
include/tvm/ffi/memory.h:
##########
@@ -45,6 +45,47 @@ typedef void (*FObjectDeleter)(void* obj, int flags);
 // - Thread-local object pools: one pool per size and alignment requirement.
 // - Can specialize by type of object to give the specific allocator to each 
object.
 namespace details {
+
+/*!
+ * \brief Allocate aligned memory.
+ * \param size The size.
+ * \tparam align The alignment.
+ * \return The pointer to the allocated memory.
+ */
+template <size_t align>
+TVM_FFI_INLINE void* AlignedAlloc(size_t size) {
+#ifdef _MSC_VER
+  // MSVC have to use _aligned_malloc
+  return _aligned_malloc(size, align);
+#else
+  if constexpr (align <= alignof(std::max_align_t)) {
+    // malloc guarantees alignment of std::max_align_t
+    return std::malloc(size);
+  } else {
+    // for other alignments, use posix_memalign
+    void* ptr;
+    int ret = posix_memalign(&ptr, align, size);
+    if (ret != 0) {
+      throw std::bad_alloc();
+    }
+    return ptr;
+  }
+#endif
+}

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   The current implementation of `AlignedAlloc` does not check the return value 
of `_aligned_malloc` and `std::malloc`. Both functions can return `nullptr` on 
allocation failure. This would lead to a null pointer dereference in 
`make_object` and `make_inplace_array` when the allocation fails. On failure, 
`std::bad_alloc` should be thrown, which is consistent with the 
`posix_memalign` path and the behavior of `new`.
   
   ```c
   TVM_FFI_INLINE void* AlignedAlloc(size_t size) {
   #ifdef _MSC_VER
     // MSVC have to use _aligned_malloc
     void* ptr = _aligned_malloc(size, align);
     if (!ptr && size > 0) {
       throw std::bad_alloc();
     }
     return ptr;
   #else
     if constexpr (align <= alignof(std::max_align_t)) {
       // malloc guarantees alignment of std::max_align_t
       void* ptr = std::malloc(size);
       if (!ptr && size > 0) {
         throw std::bad_alloc();
       }
       return ptr;
     } else {
       // for other alignments, use posix_memalign
       void* ptr;
       int ret = posix_memalign(&ptr, align, size);
       if (ret != 0) {
         throw std::bad_alloc();
       }
       return ptr;
     }
   #endif
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to