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, FALSE);
// 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_ing_array_sized_newactually defines howg_array_set_sizebehaves, i.e., whether it sets the bits to zero or not upon setting the size of the array. Indeed, the documentation of GLib saysTherefore, 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.