Skip to content

Commit 6944a8a

Browse files
committed
[TPDE] Throw bad_alloc on failed allocation if eh enabled
In case exception handling is active, we want to use throwing allocation mechanisms, so that bad_allocs are thrown instead of simply returning nullptr for failed allocations. Also use throwing operator new in BumpAllocator.
1 parent 239029a commit 6944a8a

2 files changed

Lines changed: 15 additions & 10 deletions

File tree

tpde/include/tpde/util/BumpAllocator.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class BumpAllocator {
8383

8484
private:
8585
void *allocate_mem(size_t size, std::align_val_t align) {
86-
return ::operator new(size, align, std::nothrow);
86+
return ::operator new(size, align);
8787
}
8888

8989
void deallocate_mem(void *ptr,

tpde/src/util/SmallVector.cpp

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,20 @@
77

88
#include <cstdlib>
99
#include <cstring>
10+
#include <new>
1011

1112
namespace tpde::util {
1213

14+
static void check_allocation_failure(void *ptr) {
15+
if (!ptr) {
16+
#ifdef __cpp_exceptions
17+
throw std::bad_alloc();
18+
#else
19+
fatal_error("SmallVector allocation failed");
20+
#endif
21+
}
22+
}
23+
1324
static size_t calc_new_capacity(size_t cap, size_t min_size) {
1425
size_t new_cap = 2 * cap + 1;
1526
return new_cap < min_size ? min_size : new_cap;
@@ -20,9 +31,7 @@ void *SmallVectorUntypedBase::grow_malloc(size_type min_size,
2031
size_type &new_cap) {
2132
new_cap = calc_new_capacity(cap, min_size);
2233
void *new_alloc = std::malloc(new_cap * elem_sz);
23-
if (!new_alloc) {
24-
TPDE_FATAL("SmallVector allocation failed");
25-
}
34+
check_allocation_failure(new_alloc);
2635
return new_alloc;
2736
}
2837

@@ -32,18 +41,14 @@ void SmallVectorUntypedBase::grow_trivial(size_type min_size,
3241
void *new_alloc;
3342
if (is_small()) {
3443
new_alloc = std::malloc(new_cap * elem_sz);
35-
if (!new_alloc) {
36-
TPDE_FATAL("SmallVector allocation failed");
37-
}
44+
check_allocation_failure(new_alloc);
3845
if (sz > 0) {
3946
std::memcpy(new_alloc, ptr, sz * elem_sz);
4047
}
4148
poison_memory_region(ptr, cap * elem_sz);
4249
} else {
4350
new_alloc = std::realloc(ptr, new_cap * elem_sz);
44-
if (!new_alloc) {
45-
TPDE_FATAL("SmallVector allocation failed");
46-
}
51+
check_allocation_failure(new_alloc);
4752
}
4853
ptr = new_alloc;
4954
cap = new_cap;

0 commit comments

Comments
 (0)