Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

malloc - Function free() in C isn't working for me

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...