Gus - 1 year ago 140
C Question

# 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
function, which increases the array size by 1. Here's the code:

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

int *foo;
int quantity;

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();

debugFoo();
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
. And the odd thing is that it is only incremented if the first value passed to
is even. Changing line 30 to
, 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?