给定以下 C 代码:
struct list_element
{
struct list_element * next;
};
typedef struct list_element list_element;
typedef struct
{
list_element header;
int value;
} *apple;
apple a = malloc(sizeof(apple));
a->value = 1;
free(a);
但是,程序"卡"在free()
函数中(在发布配置中,程序崩溃(。我也试图free(&a)
释放持有指针的衣服,但似乎没有任何效果。
我做错了什么?
apple a = malloc(sizeof(apple));
将使用指针大小而不是实际结构来分配内存。
避免将类型结构键入指针;
typedef struct
{
list_element header;
int value;
} apple;
apple *a = malloc(sizeof(apple ));
或 最好的方法是参考pointer
持有的type
,如下所示。
typedef struct
{
list_element header;
int value;
} *apple;
apple a = malloc(sizeof(*a));