C语言 C - 释放结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13590812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C - freeing structs
提问by user10099
Let's say I have this struct
假设我有这个结构
typedef struct person{
char firstName[100], surName[51]
} PERSON;
and I am allocating space by malloc and filling it with some values
我正在通过 malloc 分配空间并用一些值填充它
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
strcpy(testPerson->firstName, "Hyman");
strcpy(testPerson->surName, "Daniels");
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?
释放该结构占用的所有内存的正确且安全的方法是什么?是“免费(testPerson);” 足够还是我需要一个一个地释放每个结构的属性?
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);
Which means that this free(testPerson) should be equal to this free(testPerson->firstName);
这意味着这个 free(testPerson) 应该等于这个 free(testPerson->firstName);
and that's not what I want to do.
这不是我想做的。
Thanks
谢谢
回答by Omkant
Simple answer : free(testPerson)is enough .
简单的回答:free(testPerson)就够了。
Remember you can use free()only when you have allocated memory using malloc, callocor realloc.
请记住,free()只有在使用malloc,calloc或分配内存时才能使用realloc。
In your case you have only malloced memory for testPersonso freeing that is sufficient.
在你的情况下,你只有 malloced 内存,testPerson所以释放就足够了。
If you have used char * firstname , *last surNamethen in that case to store name you must have allocated the memory and that's why you had to free each member individually.
如果您使用char * firstname , *last surNamethen 在这种情况下存储名称,您必须分配内存,这就是您必须单独释放每个成员的原因。
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.
这里还有一点应该是相反的顺序;这意味着,为元素分配的内存稍后完成,因此free()它首先释放指向对象的指针。
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);
The reason behind this is, if you free the ptrobjfirst, then there will be memory leaked which is the memory allocated by firstnameand suNamepointers.
这背后的原因是,如果释放ptrobj第一,那么就会出现内存泄漏是由分配的内存firstname和suName指针。
回答by Viswesn
First you should know, how much memory is allocated when you define and allocate memory in below case.
首先您应该知道,在以下情况下定义和分配内存时分配了多少内存。
typedef struct person{
char firstName[100], surName[51]
} PERSON;
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
1) The sizeof(PERSON) now returns 151 bytes (Doesn't include padding)
1) sizeof(PERSON) 现在返回 151 个字节(不包括填充)
2) The memory of 151 bytes is allocated in heap.
2) 151 字节的内存分配在堆中。
3) To free, call free(testPerson).
3)要免费,请致电免费(testPerson)。
but If you declare your structure as
但是如果你将你的结构声明为
typedef struct person{
char *firstName, *surName;
} PERSON;
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
then
然后
1) The sizeof(PERSON) now returns 8 bytes (Doesn't include padding)
1) sizeof(PERSON) 现在返回 8 个字节(不包括填充)
2) Need to allocate memory for firstName and surName by calling malloc() or calloc(). like
2) 需要通过调用 malloc() 或 calloc() 为 firstName 和 surName 分配内存。喜欢
testPerson->firstName = (char *)malloc(100);
3) To free, first free the members in the struct than free the struct. i.e, free(testPerson->firstName); free(testPerson->surName); free(testPerson);
3)要释放,首先释放结构中的成员,而不是释放结构。即,免费(testPerson->firstName);免费(测试人->姓氏);免费(测试人);
回答by dmckee --- ex-moderator kitten
Because you defined the structas consisting of chararrays, the two strings arethe structure and freeing the structis sufficient, nor is there a way to free the structbut keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }, but then you need to allocate memory for the names separately and handle the question of when to free thatmemory.
因为你定义了struct由char数组组成,所以两个字符串是结构体,释放thestruct就足够了,也没有办法释放thestruct而保留数组。在这种情况下,您可能想要执行类似的操作struct { char *firstName, *lastName; },但是您需要分别为名称分配内存并处理何时释放该内存的问题。
Aside: Is there a reasonyou want to keep the names after the structhas been freed?
旁白:你有什么理由想struct在释放后保留名字吗?
回答by MK.
This way you only need to free the structure because the fields are arrays with static sizes which will be allocated as part of the structure. This is also the reason that the addresses you see match: the array is the first thing in that structure. If you declared the fields as char * you would have to manually malloc and free them as well.
这样您只需要释放结构,因为字段是具有静态大小的数组,将作为结构的一部分分配。这也是您看到的地址匹配的原因:数组是该结构中的第一件事。如果您将字段声明为 char *,则必须手动 malloc 并释放它们。
回答by Undeterminant
You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4)can be used in the same way that int x[4]is), calling free(firstName)would likely cause an error for the latter.
您不能释放未动态分配的类型。尽管数组在语法上是相似的(int* x = malloc(sizeof(int) * 4)可以以相同的方式使用int x[4]),但调用free(firstName)可能会导致后者出错。
For example, take this code:
例如,拿这个代码:
int x;
free(&x);
free()is a function which takes in a pointer. &xis a pointer. This code may compile, even though it simply won't work.
free()是一个接收指针的函数。&x是一个指针。这段代码可以编译,即使它根本不起作用。
If we pretend that all memory is allocated in the same way, xis "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.
如果我们假设所有内存都以相同的方式x分配,在定义处“分配”,在第二行“释放”,然后在作用域结束后再次“释放”。你不能两次释放同一个资源;它会给你一个错误。
This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at xwithout closing the program.
这甚至没有提到由于某些原因,您可能无法在x不关闭程序的情况下释放内存。
tl;dr: Just free the structand you'll be fine. Don'tcall free on arrays; only call it on dynamically allocated memory.
tl;dr:只要释放它struct,你就会没事的。不要在数组上调用 free;只在动态分配的内存上调用它。
回答by djna
Mallocs and frees need to be paired up.
Mallocs 和 frees 需要配对。
malloc grabbed a chunk of memory big enough for Person.
malloc 抓取了一块足够大的内存供 Person 使用。
When you free you tell malloc the piece of memory starting "here" is no longer needed, it knows how much it allocated and frees it.
当你释放时,你告诉 malloc 不再需要从“这里”开始的那块内存,它知道它分配了多少并释放它。
Whether you call
无论你打电话
free(testPerson)
or
或者
free(testPerson->firstName)
all that free() actually receives is an address, the same address, it can't tell which you called. Your code is much clearer if you use free(testPerson) though - it clearly matches up the with malloc.
free() 实际收到的只是一个地址,同一个地址,它无法分辨您调用的是哪个地址。如果您使用 free(testPerson),您的代码会更清晰 - 它显然与 malloc 匹配。
回答by S Dao
freeis not enough, freejust marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULLafter free.
free还不够,free只是将内存标记为未使用,结构数据将在那里直到被覆盖。为了安全起见,将指针设置为NULLafter free。
Ex:
前任:
if (testPerson) {
free(testPerson);
testPerson = NULL;
}
structis similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0so the address of first struct's member is same as the address of struct.
struct类似于数组,它是一块内存。您可以通过其偏移量访问结构成员。第一个结构体的成员放置在偏移量处,0因此第一个结构体成员的地址与结构体的地址相同。

