Differences between new/delete and malloc/free

G

Guest

What are the main difference between new/delete and malloc/free pairs ?

typedef struct {...} TMyStru;
TMyStru *P;

P = new TMyStru();
delete P;

P = (TMyStru *) malloc(sizeof(TMyStru));
free((void*)P);
 
J

John Harrison

What are the main difference between new/delete and malloc/free pairs ?

typedef struct {...} TMyStru;

This is C. In C++ you can write

struct TMyStru { ... };
TMyStru *P;

P = new TMyStru();
delete P;

P = (TMyStru *) malloc(sizeof(TMyStru));
free((void*)P);

1) new calls the TMyStru constructor, delete calls the TMyStru destructor.
malloc and free do neither of these things.

2) new throws an exception on memory exhaustion, malloc returns NULL.

Usually prefer new/delete for C++ programs, for both these reasons but
particularly the first.

john
 
J

John Harrison

John Harrison said:
This is C. In C++ you can write

struct TMyStru { ... };


1) new calls the TMyStru constructor, delete calls the TMyStru destructor.
malloc and free do neither of these things.

2) new throws an exception on memory exhaustion, malloc returns NULL.

3) new and delete are type safe (no need for casts). malloc and free are
not.

john
 
S

Sharad Kala

John Harrison said:
This is C. In C++ you can write

struct TMyStru { ... };


1) new calls the TMyStru constructor, delete calls the TMyStru destructor.
malloc and free do neither of these things.

2) new throws an exception on memory exhaustion, malloc returns NULL.

Usually prefer new/delete for C++ programs, for both these reasons but
particularly the first.

Also malloc returns a void* which then has to be cast to the appropriate
pointer type. new returns the correct pointer type itself; type safety.
malloc requires you to tell the number of bytes to allocate, new figures it
out itself.
 
C

Christopher Benson-Manica

John Harrison said:
Usually prefer new/delete for C++ programs, for both these reasons but
particularly the first.

4) Whichever you use, do not mix the two together (if you malloc it,
free it; if you new it, delete it). (for OP)
 
T

Tim Slattery

Thank you all...

NO thanks! Don't put the question in the topic and nothing in the
body!

Creating a C++ object with "new" runs the constructor of that object.
Using "delete" runs its destructor. The "malloc" function just
allocates some amount of memory and returns a pointer to it, nothing
else. "free" gets rid of memory that "malloc" allocated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top