Link to home
Start Free TrialLog in
Avatar of kmahmood
kmahmood

asked on

malloc and new???

Hi,
Can anyone pls. tell me what's the precise difference between malloc in C and new in C++. And also between free in C and delete in C++.

thanx.

KM
Avatar of slinky
slinky

How precise do you want?

with malloc you get a pointer to the number of bytes you asked for in the call, it's pretty much up to you how you use them

new returns a pointer to a new instance of the type of object you asked for, so you get type information as well as not having to work out how many bytes you need (no sizeof)


ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
malloc() allocates memory but does not initialize it in any way.  The memory will contain seemingly random informaiton left over from the last time it was used.

The new operator tries to initialize the memory.  It uses malloc() (ussually) to allocate the memory.  Then it looks to see if the object has a constructor.  If so, it calls the constructor to iniitalize the memory.  This is vital in many cases.  If you malloc memory for an object that must be initialized and the object does not get initialized it will usually cause serious problems.  New makes sure this does not happen

New has three safety features that malloc does not.  First it initializs the memory if needed.  Second, as slinky said, it insures that the right amount of memory is allocated.  If you malloc() too little space for an object it will usually cause a crash.  new prevents this.  Finally new returns a pointer of the right type.  This means you don't have to typecase the pointer returned as you do with malloc.  This prevents mistakes that occur when you typecast to the wrong type by mistake.

There is no reason to use malloc in C++.  If you want "raw" memory, use new to create an array of characters.  This is equivilant to using malloc.