Ç - 释放结构 [英] C - freeing structs
问题描述
让我们说我有这个结构
typedef struct person{
char firstName[100], surName[51]
} PERSON;
和我分配由malloc空间,并与一些值填充它。
and I am allocating space by malloc and filling it with some values
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
strcpy(testPerson->firstName, "Jack");
strcpy(testPerson->surName, "Daniels");
什么是释放由该结构所采取的一切记忆的正确和安全的方式?是自由(testPerson);足够的或者我需要一个释放的每个结构的属性吗?
What is the correct and safe way to free all memory taken by that struct? Is "free(testPerson);" enough or do I need to free each struct's attribute one by one?
这使我另一个问题 - 如何存储在内存中的结构?我注意到一个奇怪的现象 - 当我尝试打印结构地址是等于它的第一属性的地址
It leads me to another question - how are structures stored in memory? I noticed a strange behaviour - when I try to print structure address it's equal to it's first attribute's address.
printf("Structure address %d == firstName address %d", testPerson, testPerson->firstName);
这意味着,这个
免费(testPerson)
应等于这
免费(testPerson->的firstName);
Which means that this free(testPerson) should be equal to this free(testPerson->firstName);
和这不是我想做的事情。
and that's not what I want to do.
感谢
推荐答案
答案很简单:免费(testPerson)
足够
记住,你可以使用免费()
只有当您使用的malloc
分配的内存,释放calloc
或的realloc
。
Remember you can use free()
only when you have allocated memory using malloc
, calloc
or realloc
.
在你的情况,你有 testPerson
只malloc内存使释放的就足够了。
In your case you have only malloced memory for testPerson
so freeing that is sufficient.
如果您已经使用的char *姓名,*最后姓
然后在这种情况下存储姓名您必须分配的内存,这就是为什么你必须单独释放每个成员
If you have used char * firstname , *last surName
then in that case to store name you must have allocated the memory and that's why you had to free each member individually.
下面也应该以相反的顺序的一个点;这意味着,分配给元素的记忆是如此免费()
首先然后释放指针对象。
Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free()
it first then free the pointer to object.
舷每个元素你可以看到如下所示的演示:
Freeing each element you can see the demo shown below:
typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->fistname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName
.
. // do whatever you want
free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);
这背后的原因是,如果你释放 ptrobj
第一,那么就会出现内存泄漏是由姓分配的内存code>和
suName
指针。
The reason behind this is, if you free the ptrobj
first, then there will be memory leaked which is the memory allocated by firstname
and suName
pointers.
这篇关于Ç - 释放结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!