Skip to content

Commit 8731e7e

Browse files
committed
Remove redundant post-multiplication overflow check and free the old buffer if
avifAlloc() fails while resizing the array
1 parent 48f6c57 commit 8731e7e

1 file changed

Lines changed: 8 additions & 19 deletions

File tree

src/utils.c

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
#include <assert.h>
77
#include <math.h>
8-
#include <stdint.h>
98
#include <string.h>
109

1110
float avifRoundf(float v)
@@ -90,11 +89,6 @@ avifBool avifArrayCreate(void * arrayStruct, uint32_t elementSize, uint32_t init
9089
arr->elementSize = elementSize ? elementSize : 1;
9190
arr->count = 0;
9291
arr->capacity = initialCapacity;
93-
if (arr->capacity > SIZE_MAX / arr->elementSize) {
94-
arr->ptr = NULL;
95-
arr->capacity = 0;
96-
return AVIF_FALSE;
97-
}
9892
size_t byteCount = (size_t)arr->elementSize * arr->capacity;
9993
arr->ptr = (uint8_t *)avifAlloc(byteCount);
10094
if (!arr->ptr) {
@@ -111,27 +105,22 @@ void * avifArrayPush(void * arrayStruct)
111105
if (arr->count == arr->capacity) {
112106
uint8_t * oldPtr = arr->ptr;
113107
size_t oldByteCount = (size_t)arr->elementSize * arr->capacity;
114-
108+
115109
// Check for overflow before doubling the allocation size
116110
// If oldByteCount > SIZE_MAX/2, then oldByteCount * 2 would overflow
117111
if (oldByteCount > SIZE_MAX / 2) {
118-
// Cannot safely double the allocation size
119112
return NULL;
120113
}
121-
114+
122115
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);
131-
if (arr->ptr == NULL) {
132-
arr->ptr = oldPtr;
116+
117+
uint8_t * newPtr = (uint8_t *)avifAlloc(newByteCount);
118+
if (newPtr == NULL) {
119+
avifFree(oldPtr);
133120
return NULL;
134121
}
122+
123+
arr->ptr = newPtr;
135124
memset(arr->ptr + oldByteCount, 0, oldByteCount);
136125
memcpy(arr->ptr, oldPtr, oldByteCount);
137126
arr->capacity *= 2;

0 commit comments

Comments
 (0)