Skip to content

Commit 44b6270

Browse files
Copilotsyoyo
andcommitted
Fix ArenaAllocator::new_block exception safety and TypedArray::allocate overflow guard
Co-authored-by: syoyo <18676+syoyo@users.noreply.github.com>
1 parent 1eac243 commit 44b6270

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

tiny_obj_loader.h

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,10 @@ class TypedArray {
10331033
size_ = 0;
10341034
return;
10351035
}
1036+
// Guard against size_t overflow in count * sizeof(T).
1037+
if (sizeof(T) > 1 && count > SIZE_MAX / sizeof(T)) {
1038+
throw std::bad_alloc();
1039+
}
10361040
void *p = arena.allocate(count * sizeof(T), alignof(T));
10371041
data_ = static_cast<T *>(p);
10381042
size_ = count;
@@ -9831,8 +9835,18 @@ void ArenaAllocator::reset() { destroy(); }
98319835
ArenaAllocator::Block *ArenaAllocator::new_block(size_t min_bytes) {
98329836
size_t cap = (min_bytes > default_block_size_) ? min_bytes
98339837
: default_block_size_;
9834-
Block *b = new Block;
9835-
b->data = new unsigned char[cap];
9838+
// Allocate data buffer first: if this throws std::bad_alloc, no Block
9839+
// struct is leaked. If the subsequent Block allocation throws (very
9840+
// unlikely for a small POD), the data buffer is cleaned up.
9841+
unsigned char *data = new unsigned char[cap];
9842+
Block *b;
9843+
try {
9844+
b = new Block;
9845+
} catch (...) {
9846+
delete[] data;
9847+
throw;
9848+
}
9849+
b->data = data;
98369850
b->capacity = cap;
98379851
b->used = 0;
98389852
b->next = head_;

0 commit comments

Comments
 (0)