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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Allocation of memory with using different operators

Status
Not open for further replies.

Sun

Programmer
Aug 13, 1999
37
IN
Can memory allocated by malloc be" new" by using "delete",<br>
and can memory allocated by new be deleted by "free()"<br>
if this is possible thenfor what reason is this possible ?
 
<br>
I think this is possible, but a bad idea.<br>
<br>
If you look in the CRT source code, eventually they both will call _nh_malloc(). This is today. Next week they could be totally different.<br>
<br>
You really ought to code these things in matching sets. A phrase I've heard is "sandwich code", where the memory allocation and the free form the bread of the sandwich, with all the meat & good stuff inbetween.<br>
<br>
Chip H.<br>

 
It sure is a bad idea.<br>
<br>
malloc() and free() know nothing of constructors and destructors, which means they will not be called.<br>
<br>
That can lead to some very hard to find runtime bugs.<br>
<br>
Just to illustrate, take this example:<br>
<br>
class MyClass<br>
{<br>
public:<br>
<br>
MyClass();<br>
~MyClass();<br>
<br>
private:<br>
SomeOtherClass* _myCopy;<br>
};<br>
<br>
MyClass::MyClass()<br>
{<br>
_myCopy = new SomeOtherClass();<br>
}<br>
<br>
MyClass::~MyClass()<br>
{<br>
delete _myCopy;<br>
}<br>
<br>
now if you did the following, you'll be left with a leak:<br>
<br>
main()<br>
{<br>
MyClass* ptrMyClass = new MyClass();<br>
<br>
free(ptrMyClass); // Big problem: _myCopy was never deleted!<br>
<br>
}
 
Mart311 -<br>
<br>
Good point. Memory leaks from destructors not being called (for encapsulated objects) would also be a serious problem.<br>
<br>
Chip H.<br>

 
This was in case of container classes,<br>
what if a class did not have an object of<br>
some other class and u allocated memory for that class's<br>
object using &quot;new&quot; and deleted it using &quot;free&quot; ?
 
<br>
Mixing &quot;new&quot; and &quot;delete&quot; with &quot;malloc&quot; and &quot;free&quot; is<br>
never a good idea, but if your class doesn't contain<br>
other classes (either by reference or pointer) then<br>
you could do what you said.<br>
<br>
Just be forewarned that you are in dangerous ground!<br>
<br>
-Mart311<br>

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top