C++: is malloc equivalent to new?
Possible Duplicate:
What is the difference between new/delete and malloc/free?
Hi guys i am a noob in c++, want to know whether
memblock = (char *)malloc( currentByteLength);
is equivalent to
memblock = new char[currentByteLength]
in c++.
memblock = (char *)malloc( currentByteLength);
memblock = new char[currentByteLength];
No difference now. But if you replace char
with int
, then yes, there would be difference, because in that case, malloc
would allocate memory of size currentByteLength
, while new
would allocate memory of size size(int) * currentByteLength
. So be very very careful.
Also, if the type you mention in new
expression, is user-defined type, then the default constructor would be called currentByteLength
number of times, to construct the objects!
For built-in types, there is no constructor!
Almost. I mean, both allocate data on the heap, and when dealing with primitive types such as char or int, it's about the same. There's an important difference, however, when dealing with objects. new
invokes the object's constructor, while malloc
doesn't. That's because malloc
is a C function, and doesn't know anything about classes.
In general, new
is the prefered way to dynamically allocate memory in C++, since it's typesafe and easier to use. Nothing prevents you from using malloc
, but don't mix those up: do not call delete
on memory allocated with malloc
, or free
on memory allocated with new
. Bad things will happen otherwise. And do not use delete
on an array created with new[]
, or delete[]
on an object created with new
(yes, I know that's confusing, that's why you should use a vector
instead).
If the memory block is allocated with malloc()
, you have to free it by calling free()
. If it was allocated by means of new[]
, you have to delete it by calling delete []
. Using the wrong method of disposition is an error.
Also, new and malloc behave very differently when you allocate arrays of objects.
Also, they report out-of-memory condition differently - new throws an exception, malloc returns a zero.
链接地址: http://www.djcxy.com/p/13766.html上一篇: 何时使用Malloc而不是New
下一篇: C ++:是malloc等同于新的?