Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

free()

Status
Not open for further replies.

jmodo

Programmer
Aug 2, 2006
43
US
Do these 2 statements do the same thing. I mean, can I reuse the variable m after calling free? I assume that I can't use n after calling delete. Thanks!!!

MyObject* m;
m = something;
free(m);
m=somethingElse;

MyObject* n;
n = new MyObject();
delete(m);
n=something?
 
Those two statements do not do the same thing.

Your first piece of code is missing the malloc. You only call free on something you have allocated with malloc.

More importantly, you should not use malloc/free with C++ classes (there is little reason to use them at all in C++). This is because malloc does not call the MyObject constructor and free does not call the destructor.

That is the difference between malloc/free and new/delete. The C++ version calls constructors and destructors.

Finally, it is valid to assign the pointer to a new location after you have deleted it, because the pointer itself is still there. You just have to make sure you don't attempt to use the MyObject that it used to be pointing to. It might seem to work, but you would be accessing memory that has been freed to be used somewhere else and will likely end up causing a crash.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top