[英]freeing an allocation in a struct inside a struct
When I try to free an allocation in a struct inside a struct, I get an error. 当我尝试释放结构内部的结构中的分配时,出现错误。 How can I fix it?
我该如何解决?
typedef struct card
{
char* sign;
char* color;
int number;
char* name;
}card;
typedef struct deck
{
card data;
deck* next;
}deck;
deck* deleteHead(deck* head)
{
deck* curr = head;
if (head==NULL)
return head;
curr=curr->next;
if(head->data.color!=NULL)
free(head->data.color);//error
if(head->data.name!=NULL)
free(head->data.name);//error
if(head->data.sign!=NULL)
free(head->data.sign);//error
free(head);//ok
return curr;
}
when I'll delete the errors and only freeing the head - it'll work, but when I'll try to delete the allocations inside the head, I'll get a run time error. 当我删除错误并仅释放头部时,它将起作用;但是,当我尝试删除头部中的分配时,会出现运行时错误。 How can I solve this?
我该如何解决? Thank you in advance.
先感谢您。
You probably did not initialize the pointers in the card
structure. 您可能没有初始化
card
结构中的指针。 These should either be initialized to NULL
or to a pointer to memory allocated by malloc
, calloc
or strdup
. 这些应该被初始化为
NULL
或指向malloc
, calloc
或strdup
分配的malloc
的指针。
Also note that you don't need to test pointers against NULL
before calling free()
. 还要注意,在调用
free()
之前不需要测试针对NULL
指针。 free(NULL);
will gracefully return immediately, it is legal to call free
with NULL
. 将立即正常返回,使用
NULL
进行free
调用是合法的。 Incidentally it is also legal in C++ to delete
a null pointer. 顺便说一句,在C ++中
delete
空指针也是合法的。
The function can be further simplified this way: 该功能可以通过以下方式进一步简化:
deck *deleteHead(deck *head) {
deck *next = NULL;
if (head != NULL) {
next = head->next;
free(head->data.color);
free(head->data.name);
free(head->data.sign);
free(head);
}
return next;
}
The function free can only de-allocate a block of memory previously allocated by a call to malloc, calloc or realloc. free函数只能取消分配先前由对malloc,calloc或realloc的调用分配的内存块。 Your code will run without any runtime error if you initialize it properly.
如果正确初始化代码,则代码将运行而不会出现任何运行时错误。 Here's a sample code:
这是一个示例代码:
int main()
{
deck* root = (deck*)malloc(sizeof(struct deck));
root->card.color = strdup("color");
root->card.name = strdup("name");
root->card.sign = strdup("sign");
root->card.number = 2;
root->next = NULL;
root = deleteHead(root);
return 0;
}
And also there is a slight correction in your code: 而且您的代码中有一些更正:
typedef struct deck
{
card data;
struct deck* next;
}deck;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.