【问题标题】:g_slist_copy_deep returns segmentation faultg_slist_copy_deep 返回分段错误
【发布时间】:2021-12-23 12:06:42
【问题描述】:

寻求有关使用g_slist_copy_deep 复制GSList 的帮助。

我有一个GSList 的银行账户结构(帐号和描述),我想使用g_slist_copy_deepGSList 复制到另一个GSList。我的复制功能出现段错误。

首先是结构定义。

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

接下来是复制功能。

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);

}

创建主列表,然后创建临时副本。

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);

如上所述,我在尝试检索当前主帐户时遇到了段错误。 追问:我新的临时账号初始化成功后,如何添加到复制的临时账号列表中?

【问题讨论】:

    标签: c gtk3 glib


    【解决方案1】:

    g_slist_copy_deep() 在每个列表项上调用提供的复制函数,更具体地说是在项的数据上。您在此处拥有的复制函数的函数签名都错误, 并且 不返回任何内容。

    您的用例的一个可能示例如下:

    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;
    }
    

    【讨论】:

    • 您的解释和代码示例是我的救赎。我的项目按预期编译和运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多