new vs. malloc

A

Asapi

Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!
 
J

Jeffrey Schwab

Asapi said:
Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!

1. malloc() returns void*, but new returns the proper type.

2. malloc'd objects must be manually {con,de}structed.
 
A

Adam Fineman

Asapi said:
Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!
"Type-safe" loosely means that if you use the wrong type, the compiler
can tell you about it. Look at the following examples:

int* ip1 = static_cast<int*>(malloc(10 * sizeof(char)));

int* ip2 = static_cast<int*>(new char[10]);

The second line will fail to compile, whereas the first one is just fine
(at least according to the compiler).

- Adam
 
T

tom_usenet

malloc returns void*, new returns a pointer of the type of the object
created. e.g.

int* ip = malloc(sizeof(short));
//whoops! no compile time error, but runtime one

Note that the above is C code (where malloc is idiomatic), the C++
would be:

int* ip = static_cast<int*>(malloc(sizeof(short)));
//whoops! no compile time error, but runtime one

which is even more painful to write.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top