问题描述
我一直在试图通过分配)
使用空闲内存的malloc(免费()
。
一些结构的它免费的,但留下了一些他们的方式,他们也仍然与他们的孩子。它也永远不会释放根(gRootPtr)
为二叉树。
我用X code,以找出是否由二叉树使用的内存已被释放,也可以使用if语句。
code我使用的释放内存:
无效FreeMemory(InfoDefiner * InfoCarrier)
{
如果((* InfoCarrier)!= NULL){
FreeMemory((及(* InfoCarrier) - >左侧));
FreeMemory((及(* InfoCarrier) - >右));
免费((* InfoCarrier));
}
}
code,我使用的是看如果内存已经被释放。
如果(gRootPtr!= NULL){
返回1;
}
其他{
返回0;
}
首先,免费不改变的指针的本身。
无效* X =的malloc(1);
免费(X);
断言(X!= NULL); // x将不会返回NULL
如果您希望指针返回NULL,你必须做你自己。
其次,没有关于将发生到存储器什么guarentees所指向指针的自由后:
为int * X =的malloc(sizeof的(INT));
* X = 42;
免费(X);
// * x的vlaue未定义;它可以是42,它可以是0,
//它可能会崩溃,如果你触摸它,它可能会做一些更糟糕!
请注意,这意味着你的无法实际测试的如免费()
的作品。严格地说,这是合法的免费()
通过绝对无为来实现(虽然你会耗尽内存最终如果这是当然的情况下)。
I have been trying to free memory allocated via malloc()
using free()
.
Some of the structs it does free but leaves some the way they were and they also remain linked to their children. It also never frees the root (gRootPtr)
for a binary tree.
I am using Xcode to find out if the memory used by the binary tree has been freed and also use the if statement.
Code I am using to free the memory:
void FreeMemory(InfoDefiner *InfoCarrier)
{
if ((*InfoCarrier) != NULL) {
FreeMemory((&(*InfoCarrier)->left));
FreeMemory((&(*InfoCarrier)->right));
free((*InfoCarrier));
}
}
Code I am using to see if the memory has been freed.
if (gRootPtr != NULL) {
return 1;
}
else{
return 0;
}
First, free does not change the pointer itself.
void *x = malloc(1);
free(x);
assert(x != NULL); // x will NOT return to NULL
If you want the pointer to go back to NULL, you must do this yourself.
Second, there are no guarentees about what will happen to the memory pointed to by the pointer after the free:
int *x = malloc(sizeof(int));
*x = 42;
free(x);
// The vlaue of *x is undefined; it may be 42, it may be 0,
// it may crash if you touch it, it may do something even worse!
Note that this means that you cannot actually test if free()
works. Strictly speaking, it's legal for free()
to be implemented by doing absolutely nothing (although you'll run out of memory eventually if this is the case, of course).
这篇关于免费功能(c)中工作不适合我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!