【问题标题】:g_object_set_data has memory holesg_object_set_data 有内存漏洞
【发布时间】:2019-02-11 18:22:04
【问题描述】:

我正在制作一个 GTK3 应用程序,并在 GtkListBoxRow 上使用 g_object_set_qdata 进行搜索。

我使用这个代码:

GArray      *complib;
#define row_get_entry(row) (ElcCompLibEntry*)g_object_get_qdata(G_OBJECT(row),registryquark)
GtkWidget* elc_registry_listbox_make_item(ElcCompLibEntry* curritem)
{
  /* I remove UI creation */
  GtkWidget* intermediate = gtk_list_box_row_new();
  gtk_container_add(GTK_CONTAINER(intermediate),GTK_WIDGET(mainbox));
  gtk_widget_show_all(GTK_WIDGET(intermediate));
  g_object_set_qdata(G_OBJECT(intermediate),registryquark,curritem);
  return intermediate;
};
  static GtkWidget* saved = NULL;
  GtkWidget* new=elc_registry_listbox_make_item(entry);
  gtk_container_add(GTK_CONTAINER(listbox->real_listbox),new);
  if (saved)
    g_debug("saved entry is at position %d",((gintptr)row_get_entry(saved)-(gintptr)complib->data)/sizeof(ElcCompLibEntry));
  saved=new;
  g_debug("entry is at position %d",((gintptr)row_get_entry(new)-(gintptr)complib->data)/sizeof(ElcCompLibEntry));

我的程序的输出:

** (elc:9906): DEBUG: 18:51:10.623: entry is at position 0

** (elc:9906): DEBUG: 18:51:10.625: saved entry is at position -14015
** (elc:9906): DEBUG: 18:51:10.625: entry is at position 1

** (elc:9906): DEBUG: 18:51:10.627: saved entry is at position 32
** (elc:9906): DEBUG: 18:51:10.627: entry is at position 2

** (elc:9906): DEBUG: 18:51:10.629: saved entry is at position 2
** (elc:9906): DEBUG: 18:51:10.629: entry is at position 3

** (elc:9906): DEBUG: 18:51:10.631: saved entry is at position 25921
** (elc:9906): DEBUG: 18:51:10.631: entry is at position 4

ElcCompLibEntry 是一个简单的结构。 g_object_set_qdata_full 只是破坏了旧数据,夸克被初始化,即使在主线程中运行它我也得到了相同的结果(只有 saved entry is at position 2 是恒定的)。

有人可以帮助找到问题的根源和/或将我发送到相关文档吗?

感谢您的宝贵时间!

【问题讨论】:

    标签: gtk3 glib


    【解决方案1】:

    https://developer.gnome.org/glib/stable/glib-Arrays.html#GArray

    数据可能会随着元素添加到 GArray 中而移动。

    如果没有看到创建并附加到 complib 的代码,很难判断,但 complib->data 不是常量,并且当数组调整大小时,存储在 qdata 中的指针可能会失效。

    为防止这种情况发生,请尝试使用 g_array_sized_new() 预分配您需要的元素数量来创建数组。

    【讨论】:

    • 哦,是的...现在我使用 GPtrArray 和 malloc()。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多