我正在尝试使用realloc
实现dinamically增加的数组。我创建malloc
的数组,然后叫我add
功能,1。此处增加数组的大小是代码:realloc bug - 增加数组的最后一个元素
#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;
}
然而,当我运行它,我得到以下的输出:
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
正如您所看到的,第二次调用add
时,foo [3]的值会加1。而奇怪的是,只有当传递给add
的第一个值是偶数时才会增加。更改第30行至add(21)
,我得到下面的输出:
[...]
foo[2] = 3
foo[3] = 21
foo[0] = 1
foo[1] = 2
foo[2] = 3
foo[3] = 21
foo[4] = 2
这是一个bug,或我使用realloc
错了吗?
您不需要投射malloc结果。你可以改变'foo =(int *)malloc(quantity * sizeof(int));'to'foo = malloc(quantity * sizeof * foo);' – sjsam
[Compiler Bug](http://c2.com/cgi/wiki?CompilerBug) –