Skip to content

[BUG] dynarray_push() uses wrong index after incrementing length #5

Description

@seesee010

Bug Description

dynarray_push() increments length before calling set(), causing it to write to the wrong index.

Location

src/modify.c lines 122-123

Current Code

array->length++;
isOk = dynarray_set(array, array->length, value);  // Uses length as index!

Problem

  1. Increments length first (e.g., 0 → 1)
  2. Then calls set(array, length, value) which tries to set index 1
  3. Arrays are 0-indexed, so first element should be at index 0
  4. Skips the first position and writes to wrong indices

Expected Behavior

Should set at current length, then increment.

Proposed Fix

isOk = dynarray_set(array, array->length, value);
if (isOk) {
    array->length++;
}
return isOk;

Impact

  • Severity: High
  • First element never gets written
  • All elements written to wrong positions
  • Combined with set() bugs, causes complete failure

Reproduction

DynArray *arr = dynarray_create(sizeof(int), 10);
int val1 = 10, val2 = 20;

dynarray_push(arr, &val1);
printf("Length after first push: %zu\n", dynarray_length(arr));  // Shows 1
printf("Should have written to index 0, but wrote to index 1\n");

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