Skip to content

Commit c0b1e05

Browse files
committed
Improve Hashtable_put() buffer grow conditions
The conditions for growing the buffer was off by one. Also improve the "grow factor" multiplication slightly so that it cannot overflow for any value <= SIZE_MAX * 7. If `Hashtable.size > SIZE_MAX / sizeof(HashtableItem)`, the buffer allocation would fail at xCalloc(), and one conditional for checking `size` overflow can be omitted. Let compilers omit that as an optimization. Signed-off-by: Kang-Che Sung <explorer09@gmail.com>
1 parent 041c644 commit c0b1e05

1 file changed

Lines changed: 5 additions & 5 deletions

File tree

Hashtable.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,21 +222,21 @@ void Hashtable_put(Hashtable* this, ht_key_t key, void* value) {
222222

223223
assert(Hashtable_isConsistent(this));
224224
assert(this->size > 0);
225+
assert(this->size <= SIZE_MAX / sizeof(HashtableItem));
225226
assert(value);
226227

227228
/* grow on load-factor > 0.7 */
228-
if (10 * this->items > 7 * this->size) {
229-
if (SIZE_MAX / 2 < this->size)
230-
CRT_fatalError("Hashtable: size overflow");
229+
if (sizeof(HashtableItem) < 7 && SIZE_MAX / 7 < this->size)
230+
CRT_fatalError("Hashtable: size overflow");
231231

232+
if (this->items >= this->size * 7 / 10)
232233
Hashtable_setSize(this, 2 * this->size);
233-
}
234234

235235
insert(this, key, value);
236236

237237
assert(Hashtable_isConsistent(this));
238238
assert(Hashtable_get(this, key) != NULL);
239-
assert(this->size > this->items);
239+
assert(this->size >= this->items);
240240
}
241241

242242
void* Hashtable_remove(Hashtable* this, ht_key_t key) {

0 commit comments

Comments
 (0)