按预期方式初始化时不清除GArray

时间:2011-02-26 16:55:30

标签: c arrays glib

我有一些奇怪的Glib行为,在互联网上搜索了一下,找到this Glib tutorial,第二个代码块是具体的:

//ex-garray-2.c
#include <glib.h>
#include <stdio.h> // I added this to make it compile
int main(int argc, char** argv) {
    GArray* a = g_array_sized_new(TRUE, TRUE, sizeof(int), 16);
    printf("Array preallocation is hidden, so array size == %d\n", a->len);
    printf("Array was init'd to zeros, so 3rd item is = %d\n",
        g_array_index(a, int, 2));
    g_array_free(a, FALSE);

    // I removed some code here

    return 0;
}

所以,预期的结果应该是

Array preallocation is hidden, so array size == 0
Array was init'd to zeros, so 3rd item is = 0

但我确实

Array preallocation is hidden, so array size == 0
Array was init'd to zeros, so 3rd item is = 901959560

我使用gcc 4.5.3,glibc 2.13和glib 2.26.1运行Gentoo Linux~amd64(64位,测试)。我使用gcc $(pkg-config --cflags --libs glib-2.0) -o ex-garray-2 ex-garray-2.c

编译了程序

我知道为什么我会得到观察到的行为而不是预期的行为?

2 个答案:

答案 0 :(得分:3)

我对GLib不太熟悉,但我发现它的文档非常误导:clear_中的标志g_array_sized_new实际上定义了g_array_set_size的行为方式,即它是否将位设置为设置数组的大小时是否为 。的确,GLib的documentation

  

g_array_sized_new创建一个新的GArray,其中预先分配了reserved_size元素,引用计数为1.这样可以避免频繁的重新分配,如果要向阵列中添加许多元素。 请注意,数组的大小仍为0.

因此,您尝试访问索引大于数组大小的元素。首先尝试使用g_array_set_size (a,16)设置数组的大小,然后只能访问第3项。

答案 1 :(得分:-1)

IBM文档不正确。你必须像这样取消引用g_array_index():

printf("%d\n", &g_array_index(array, type, index));

请参阅http://developer.gnome.org/glib/2.28/glib-Arrays.html#g-array-index