【问题标题】:Using Memory Allocation with glib's g_new()将内存分配与 glib 的 g_new() 一起使用
【发布时间】:2017-05-11 03:47:11
【问题描述】:

我一直在使用 g_new() 为单个结构分配内存,可以通过以下方式。

/*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);
}

我现在正在尝试对结构的数组 [2] 执行相同的操作,例如 静态分配是这样的,但这意味着它在程序堆栈上。

h_item my_h_item[5];

我想动态分配上面一样的,但是运行程序的时候好像有问题……

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

这个程序可以编译但是有段错误...

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

我的分配哪里出错了?

【问题讨论】:

  • my_h_item[2] = g_new(h_item, 2); 越界访问。

标签: c memory-management struct heap-memory glib


【解决方案1】:

您已经分配了 my_h_item[2] 并且您正在访问未分配的 my_h_item[0]

您还需要在使用其元素之前分配 my_h_item[0]

my_h_item[2] 无效,因为 my_h_item 只有 2 个元素,只有 my_h_item[0] 和 my_h_item[1] 有效

【讨论】:

  • 没错,我在回答中添加了这一点
【解决方案2】:

您说您想创建一个包含 2 个结构的数组。 您创建的是一个由两个指针组成的数组。

你需要做的是

static h_item * my_h_item;

然后

h_item = g_new(h_item, 2);

然后您可以将这两个结构用作h_item[0]h_item[1],并将其中的日期用作

h_item[0].data = g_strdup(...);

g_* 类函数也是非标准的。请使用 malloc 和 free。

【讨论】:

  • 谢谢...没有注意到 [2] 越界。
  • @NatenBaptista 这不是你的问题,而是。当您只需要一个指针时,您已经声明了一个指针数组。
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多