diff --git a/sycl/include/sycl/usm/usm_allocator.hpp b/sycl/include/sycl/usm/usm_allocator.hpp index 6ae1da5a3e350..31d9c5ec9a955 100644 --- a/sycl/include/sycl/usm/usm_allocator.hpp +++ b/sycl/include/sycl/usm/usm_allocator.hpp @@ -71,6 +71,9 @@ class usm_allocator { T *allocate(size_t NumberOfElements, const detail::code_location CodeLoc = detail::code_location::current()) { + if (!NumberOfElements) + return nullptr; + auto Result = reinterpret_cast( aligned_alloc(getAlignment(), NumberOfElements * sizeof(value_type), MDevice, MContext, AllocKind, MPropList, CodeLoc)); diff --git a/sycl/test-e2e/USM/usm_allocator_zero_allocation.cpp b/sycl/test-e2e/USM/usm_allocator_zero_allocation.cpp new file mode 100644 index 0000000000000..b8aace8933c28 --- /dev/null +++ b/sycl/test-e2e/USM/usm_allocator_zero_allocation.cpp @@ -0,0 +1,30 @@ +// RUN: %{build} -o %t.out +// RUN: %{run} %t.out + +#include + +using namespace sycl; + +template void test(queue &q) { + sycl::usm_allocator ua(q); + int *p = ua.allocate(0); + + assert(!p && "Our implementation of usm_allocator is expected to return a " + "null pointer when allocation size is zero."); + + ua.deallocate(p, 0); +} + +int main() { + queue q; + auto dev = q.get_device(); + + if (dev.has(aspect::usm_host_allocations)) { + test(q); + } + if (dev.has(aspect::usm_shared_allocations)) { + test(q); + } + + return 0; +}