By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,659 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

new vs. malloc

P: n/a
Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!
Jul 22 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
On Tue, 16 Dec 2003 18:50:34 GMT, "Asapi" <As***@net.net> wrote:
Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!


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

vs
int* ip = new short;
//compile time error, short* not convertible to int*

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #2

P: n/a
Asapi wrote:
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

--
Reverse domain name to reply.

Jul 22 '05 #3

P: n/a
Asapi wrote:
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.

Jul 22 '05 #4

P: n/a
On Tue, 16 Dec 2003 19:05:13 +0000, tom_usenet
<to********@hotmail.com> wrote:
On Tue, 16 Dec 2003 18:50:34 GMT, "Asapi" <As***@net.net> wrote:
Compared to malloc(), why would one say that the 'new' operator is type-safe
in a book? Thanks!


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
Jul 22 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.