2016-07-28 76 views
-1

我正在尝试使用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错了吗?

+0

您不需要投射malloc结果。你可以改变'foo =(int *)malloc(quantity * sizeof(int));'to'foo = malloc(quantity * sizeof * foo);' – sjsam

+0

[Compiler Bug](http://c2.com/cgi/wiki?CompilerBug) –

回答

5

sizeof(foo)不是分配的缓冲区的大小,但的foo的大小,这是int*。使用保存的元素数来计算新的缓冲区大小。

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

[相同想法](http://ideone.com/8VwKoX) – imbearr

1

sizeof(foo)总是返回你同样的价值,大概4。由于sizeof操作符将返回你的int *

大小你有“正确地”宣布全球范围内变量(quantity)存储电流的大小你的数组,使用该变量到realloc你的结构,就像你用malloc做的那样。

void add(int number) { 
    quantity++; 
    foo = realloc(foo, (quantity * sizeof(int))); 
    if (foo != NULL) 
    { 
     foo[quantity-1] = number; 
    } 
    else 
    { 
     fprintf(stderr, "Failed to add number.\n"); 
    } 
} 

请注意,始终检查函数返回值非常重要。 正如realloc返回值的示例所示,您必须对mallocmain函数执行相同的操作。

int main() { 
    quantity = 3; 
    foo = malloc(quantity * sizeof(int)); 
    if (foo != NULL) 
    { 
     foo[0] = 1; 
     foo[1] = 2; 
     foo[2] = 3; 

     debugFoo(); 

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

     return 0; 
    } 
    else 
    { 
     fprintf(stderr, "Failed to allocate array.\n"); 
     return 1; 
    } 
} 
+0

此代码包含错误。 - 它似乎是固定的。 – MikeCAT

+0

所以downvoter,我正在编辑。可以让我呼吸....? – LPs

+0

@MikeCAT我严重按下“发布您的答案”按钮... :) – LPs