开发者

GArray is not cleared on initialization as expected

I was having some weird Glib behavior, searched the internet a little and found this Glib tutorial, the second code block to be specific:

//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, 开发者_如何学CFALSE);

    // I removed some code here

    return 0;
}

So, the expected result should be

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

but I do get

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

I am running Gentoo Linux ~amd64 (64bit, testing) with gcc 4.5.3, glibc 2.13 and glib 2.26.1. I compiled the program using gcc $(pkg-config --cflags --libs glib-2.0) -o ex-garray-2 ex-garray-2.c

Any idea why I get the observed behavior and not the expected one?


I am not very familiar with GLib, but I found its documentation very misleading: the flag clear_ in g_array_sized_new actually defines how g_array_set_size behaves, i.e., whether it sets the bits to zero or not upon setting the size of the array. Indeed, the documentation of GLib says

g_array_sized_new creates a new GArray with reserved_size elements preallocated and a reference count of 1. This avoids frequent reallocation, if you are going to add many elements to the array. Note however that the size of the array is still 0.

Therefore, you are trying to access an element whose index is larger than the size of the array. Try to set the size of the array using g_array_set_size (a,16) first, and then only you can access the 3rd item.


The IBM documentation isn't correct. You have to dereference g_array_index() like this:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜