Home > OS >  g_slist_copy_deep returns segmentation fault
g_slist_copy_deep returns segmentation fault

Time:11-11

Looking for assistance on copying a GSList using g_slist_copy_deep.

I have a GSList of bank accounts structs (account number and description), and I want to use g_slist_copy_deep to copy that GSList to another GSList. I get a seg fault in my copy function.

First the structure definition.

typedef struct Accounts {
    gchar number[100];
    gchar description[500];
} Account;

Next, the copy function.

GCopyFunc build_temporary_list(gpointer master_account, gpointer user_data) {

    /* Retrieve current master account */
    GSList *master_account_ptr = (GSList *)master_account_list;
    Account * account_ptr = (Account *)master_account_ptr->data;
    Account master_account = *account_ptr; /*Seg fault here */

    /* Copy master account into a new temporary account */
    Account temporary_account;
    strcpy(temporary_account.number,master_account.number);
    strcpy(temporary_account.description,master_account.description);

}

Creating the master list and then the temporary copy.

GSList *master_account_list = read_account_numbers(); /* This statment works correctly, producing a GSList with four accounts. */

GSList *temporary_account_list = g_slist_copy_deep(master_account_list, (GCopyFunc) build_temporary_list, NULL);

As noted above, I get a seg fault when attempting to retrieve the current master account. Follow up question: After I successfully initialize a new temporary account, how is it added to the list of copied temporary accounts?

CodePudding user response:

g_slist_copy_deep() calls the provided copy function on each list item, more specifically on the item's data. The copy function you have here gets both the function signature wrong, and doesn't return anything.

A possible example for your use case could be the following:

gpointer build_temporary_list(gpointer item, gpointer user_data) {
    Account *master_account = item;

    /* Copy master account into a new temporary account */
    Account* temp_account = g_new (Account, 1);
    strcpy(temp_account->number, master_account->number);
    strcpy(temp_account->description, master_account->description);

    return temp_account;
}
  • Related