Search code examples
cmemory-managementstructheap-memoryglib

Using Memory Allocation with glib's g_new()


I have been using g_new() to allocate memory for a single struct which is ok in the following manner.

/*Structure*/
typedef struct
{
    guint16 index;
    gchar * date;
    gchar * number;
}h_item;

/*allocation*/
h_item * my_h_item = g_new(h_item, 1);

/*freeing function*/
void free_h_item(h_item * item)
{
    g_free(item->date);
    g_free(item->number);
    g_free(item);
}

I am now trying to do the same for an array[2] of the structs, for example statically allocation is like this, but that would mean it's on the program stack.

h_item my_h_item[5];

I would like to dynamically allocate the same above, but I seem to have trouble when running the program...

/*Structure*/
typedef struct
{
    guint16 index;
    gchar * date;
    gchar * number;
}h_item;


/*freeing function*/
void free_h_item(h_item * item)
{
    g_free(item->date);
    g_free(item->number);
    g_free(item);
}

static h_item * my_h_item[2];

int main()
{
    /*allocation*/
    my_h_item[2] = g_new(h_item, 2);

    my_h_item[0]->date = g_strdup("12345"); /*Test*/
    return 0;
}

This program compiles but segfaults...

#0  0x00000000004007a7 in main () at struct_memory.c:30
30      my_h_item[0]->date = g_strdup("12345"); /*Test*/

Where is my allocation going wrong?


Solution

  • You have allocated my_h_item[2] and you are accesing my_h_item[0] which is not allocated

    You need to allocate my_h_item[0] as well prior to using its elements

    my_h_item[2] is not valid as my_h_item has only 2 elements, only my_h_item[0] and my_h_item[1] is valid