Skip to content

Commit

Permalink
[SYCL] Return nullptr when allocation size is zero in usm allocator (#…
Browse files Browse the repository at this point in the history
…12765)

Currently, usm allocator throws when the allocation size is zero.
However, this behavior is not aligned with that of std::allocator.
Refer KhronosGroup/SYCL-Docs#355 for
discussion regarding this. The spec says that the allocation functions
must succeed when the size is zero. The value returned in this case is
unspecified (it can either be a NULL pointer or a non-NULL pointer)

This PR makes USM allocator return a null pointer when the allocation
size is zero.
  • Loading branch information
uditagarwal97 authored Feb 21, 2024
1 parent feb7722 commit 7f51d92
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions sycl/include/sycl/usm/usm_allocator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<T *>(
aligned_alloc(getAlignment(), NumberOfElements * sizeof(value_type),
MDevice, MContext, AllocKind, MPropList, CodeLoc));
Expand Down
30 changes: 30 additions & 0 deletions sycl/test-e2e/USM/usm_allocator_zero_allocation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// RUN: %{build} -o %t.out
// RUN: %{run} %t.out

#include <sycl/sycl.hpp>

using namespace sycl;

template <usm::alloc alloc_kind> void test(queue &q) {
sycl::usm_allocator<int, alloc_kind> 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<usm::alloc::host>(q);
}
if (dev.has(aspect::usm_shared_allocations)) {
test<usm::alloc::shared>(q);
}

return 0;
}

0 comments on commit 7f51d92

Please sign in to comment.