Search code examples
cmemory-managementrealloc

realloc bug - incrementing last element of array


I am trying to implement a dinamically increasing array with realloc. I create the array with malloc, and then call my add function, which increases the array size by 1. Here's the code:

#include <stdio.h>
#include <stdlib.h>

int *foo;
int quantity;

void add(int number) {
    foo = (int*) realloc(foo, sizeof(foo) + sizeof(int));
    foo[quantity] = number;
    quantity++;
}

void debugFoo() {
    for (int i = 0; i < quantity; i++) {
        printf("foo[%i] = %i\n", i, foo[i]);
    }
    printf("\n");
}

int main() {
    quantity = 3;
    foo = (int*) malloc(quantity * sizeof(int));

    foo[0] = 1;
    foo[1] = 2;
    foo[2] = 3;

    debugFoo();

    add(20);
    debugFoo();
    add(2);
    debugFoo();

    return 0;
}

However when I run it, I get the following output:

foo[0] = 1
foo[1] = 2
foo[2] = 3

foo[0] = 1
foo[1] = 2
foo[2] = 3
foo[3] = 20

foo[0] = 1
foo[1] = 2
foo[2] = 3
foo[3] = 21
foo[4] = 2

As you can see, the value of foo[3] is incremented by 1 the second time I call add. And the odd thing is that it is only incremented if the first value passed to add is even. Changing line 30 to add(21), I get the following output:

[...]
foo[2] = 3
foo[3] = 21

foo[0] = 1
foo[1] = 2
foo[2] = 3
foo[3] = 21
foo[4] = 2

Is this a bug or am I using realloc wrong?


Solution

  • sizeof(foo) is not the size of allocated buffer but the size of foo, which is int*. Use saved number of elements to calculate new buffer size.

    foo = (int*) realloc(foo, sizeof(int) * (quantity + 1));