Skip to content

Commit 13783aa

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 2a4a06f commit 13783aa

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
@@ -105,7 +105,23 @@ void * avifArrayPush(void * arrayStruct)
105105
if (arr->count == arr->capacity) {
106106
uint8_t * oldPtr = arr->ptr;
107107
size_t oldByteCount = (size_t)arr->elementSize * arr->capacity;
108-
arr->ptr = (uint8_t *)avifAlloc(oldByteCount * 2);
108+
109+
// Check for overflow before doubling the allocation size
110+
// If oldByteCount > SIZE_MAX/2, then oldByteCount * 2 would overflow
111+
if (oldByteCount > SIZE_MAX / 2) {
112+
// Cannot safely double the allocation size
113+
return NULL;
114+
}
115+
116+
size_t newByteCount = oldByteCount * 2;
117+
118+
// Additional safety check: verify the multiplication didn't overflow
119+
if (newByteCount < oldByteCount) {
120+
// Overflow occurred despite the check (shouldn't happen, but defense in depth)
121+
return NULL;
122+
}
123+
124+
arr->ptr = (uint8_t *)avifAlloc(newByteCount);
109125
if (arr->ptr == NULL) {
110126
return NULL;
111127
}

0 commit comments

Comments
 (0)