Skip to content

[BUG] dynarray_push() doubles capacity twice causing memory waste #4

Description

@seesee010

Bug Description

When dynarray_push() needs to resize, it increases capacity twice: once via dynarray_inc() and again by multiplying capacity by itself.

Location

src/modify.c lines 112-119

Current Code

if (array->length >= array->capacity) {
    isOk = dynarray_inc(array, array->capacity);  // capacity: 2 → 4
    
    if (!isOk) {
        return false;
    }

    array->capacity *= array->capacity;  // capacity: 4 → 16 !!
}

Problem

  1. dynarray_inc(array, array->capacity) already doubles the capacity
  2. Then multiplying again causes exponential growth: 2 → 4 → 16 → 256 → 65536!
  3. Wastes massive amounts of memory

Expected Behavior

Should double capacity once: 2 → 4 → 8 → 16 → 32

Proposed Fix

if (array->length >= array->capacity) {
    size_t new_capacity = array->capacity == 0 ? 1 : array->capacity * 2;
    if (!dynarray_setSize(array, new_capacity)) {
        return false;
    }
}

Impact

  • Severity: High
  • Memory waste (16x more than needed after first resize)
  • Performance impact from unnecessary reallocations

Reproduction

DynArray *arr = dynarray_create(sizeof(int), 2);
printf("Initial capacity: %zu\n", dynarray_capacity(arr));  // 2

int val = 10;
dynarray_push(arr, &val);
dynarray_push(arr, &val);
dynarray_push(arr, &val);  // Triggers resize

printf("After resize: %zu\n", dynarray_capacity(arr));  // Shows 16 instead of 4!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions