Skip to content

Commit 48f6c57

Browse files
committed
Prevent integer overflow during buffer reallocation
Add pre- and post-multiplication checks when doubling allocation sizes to prevent size_t overflow leading to undersized allocations and potential heap corruption during memcpy. Includes defensive overflow detection and early failure on unsafe growth.
1 parent fa8db07 commit 48f6c57

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

src/utils.c

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,23 @@ void * avifArrayPush(void * arrayStruct)
111111
if (arr->count == arr->capacity) {
112112
uint8_t * oldPtr = arr->ptr;
113113
size_t oldByteCount = (size_t)arr->elementSize * arr->capacity;
114-
arr->ptr = (uint8_t *)avifAlloc(oldByteCount * 2);
114+
115+
// Check for overflow before doubling the allocation size
116+
// If oldByteCount > SIZE_MAX/2, then oldByteCount * 2 would overflow
117+
if (oldByteCount > SIZE_MAX / 2) {
118+
// Cannot safely double the allocation size
119+
return NULL;
120+
}
121+
122+
size_t newByteCount = oldByteCount * 2;
123+
124+
// Additional safety check: verify the multiplication didn't overflow
125+
if (newByteCount < oldByteCount) {
126+
// Overflow occurred despite the check (shouldn't happen, but defense in depth)
127+
return NULL;
128+
}
129+
130+
arr->ptr = (uint8_t *)avifAlloc(newByteCount);
115131
if (arr->ptr == NULL) {
116132
arr->ptr = oldPtr;
117133
return NULL;

0 commit comments

Comments
 (0)