【发布时间】: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