3

Possible Duplicate:
What is the difference between new/delete and malloc/free?

I am a noob in c++, want to know whether

memblock = (char *)malloc( currentByteLength); 

is equivalent to

memblock = new char[currentByteLength]

in c++?

peterh
  • 11,875
  • 18
  • 85
  • 108
karthick
  • 11,998
  • 6
  • 56
  • 88
  • 1
    Have you tried them both? Have you observed any differences? – abelenky Feb 09 '11 at 16:54
  • I am trying to use this in alchemy and i find that the ordering is completely different. So what is the equivalent of memblock = new char[currentByteLength] – karthick Feb 09 '11 at 16:57
  • 4
    @abelenky: That's never a good way to discover how the language works. You need to read the docs. Case in point: In this specific example, the behavior will not be observable different. Nevertheless, `malloc` and `new` are very much not the same! – John Dibling Feb 09 '11 at 17:01
  • 4
    [Duplicate1](http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free), [duplicate2](http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new), [duplicate3](http://stackoverflow.com/questions/2983182/new-delete-malloc-free), [duplicate4](http://stackoverflow.com/questions/807939/what-is-the-difference-between-new-and-malloc-and-calloc-in-c). Come on, guys, please search before asking questions. –  Feb 09 '11 at 17:01
  • @Øystein maybe a warning should show up whenever malloc and new are mentioned in the question :) – Foo Bah Feb 09 '11 at 17:07
  • 1
    @karthick - beware here, most SO people don't actually understand this issue too well. For instance, the first sentence of the top voted answer is just plain incorrect. Both versions do not allocate on the heap. The free-store (what new allocates from) MAY be implemented with the heap but doesn't have to be. See my answer. – Edward Strange Feb 09 '11 at 17:17

10 Answers10

8
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!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Correct, that would require malloc * sizeof(int). But you're missing the point, the real difference is the constructor/destructor call. – Stefan Steiger Feb 09 '11 at 17:00
  • @Quandary: I added that also. In fact I was adding that when you're writing that comment! – Nawaz Feb 09 '11 at 17:03
  • 1
    Why was this downvoted? what he said is correct. – Argote Feb 09 '11 at 17:06
  • 2
    seems that someone downvoted almost every answer here... not sure the point of that. hopefully they'll explain why. – tenfour Feb 09 '11 at 17:11
  • @Downvoters : Can you please explain why you downvoted it? What exactly is wrong in it? Please point it out. – Nawaz Feb 09 '11 at 17:25
  • @Nawaz: I downvoted because `malloc` and `new[]` do not do the same thing as each other. `malloc` must be matched by `free`, and `new[]` must be matched by `delete[]`. – Mankarse May 09 '12 at 10:17
3

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).

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
3

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.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
2

The new keyword allocates memory in the free-store. The malloc function allocates memory in the heap.

Many implementations use the heap to implement the free-store, but they don't have to be related at all. They can, and often do, have completely different managers.

As far as your code should be concerned, the memory blocks allocated by your particular examples could be considered equivalent. This is a pretty corner case though and you still need to make sure you deallocate the block in the correct place (free-store vs. heap). It's better if you just never consider them the same thing at all.

Here's a good tutorial on memory in C++: http://www.gotw.ca/gotw/009.htm

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
1

not exactly, malloc() is C function and new is C++ operator, also if your case their a both allocate buffer but if malloc() fails then is return NULL. but if new fails is throw an exception.

for more info read this session in C++ FAQ

Baget
  • 3,318
  • 1
  • 24
  • 44
1

Short answer: Yes, that is how you allocate memory dynamically in C++.

Long answer: No, they are different beasts. The most obvious difference is that memory that is malloc()'ed must be free()'ed, while memory that is new'ed must be deleted.

new calls the default constuctor of the type, is type-safe, throws an exception on error, and can be overridden.

In C++, you should always be using new over malloc(), unless you need to interface with code written in C.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
0

Yes:

  1. They have different spellings (duh :P)
  2. They require different methods of freeing the memory (malloc / free vs. operator new[] / operator delete[])
  3. When they fail, they have different behaviors. malloc returns 0, operator new[] throws an exception.

This is only in your particular case though. There are even more differences when:

  1. You are allocating non-POD objects (here, constructors & destructors get called)
  2. The elements are non-char-sized (here, you need to do a bit of math for malloc -- this would illustrate how operator new is more intuitive for allocating objects instead of a blob)

I don't think this is a great question... what are you really asking? Difference in terms of what? No, you cannot interchange them blindly.

tenfour
  • 36,141
  • 15
  • 83
  • 142
0

It is roughly equivalent (exception/null and constructor aside) in the case that char is 1 byte in size, otherwise for the first one you should multiply by the data type size.

memblock = (char *)malloc( currentByteLength * sizeof(char) ); 
Argote
  • 2,155
  • 1
  • 15
  • 20
0

Note that

memblock = new DATATYPE[length]

is equivalent to

memblock = (DATATYPE*) malloc(length * sizeof(DATATYPE));

If and only if there is no constructor, and if and only if datatype is not a pointer itselfs.

Free and delete are equivalent only if there's no destructor.

If there's no constructor/destructor, you can call new/malloc delete/free interchangably and even with mixing.

new and delete create the memory for a new object calling the constructor/destructor (if available), while malloc and free just allocate the memory (without calling constructor/destructor).

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
0

The main differences (specifically referring to char) are:

  • How to actually clear the memory at the end [first uses free, second uses delete]
  • Sizes may be different (if char is actually a wide 2-byte character, then the first allocates only enough space for currentByteLength bytes whereas the new allocates currentByteLength * 2 bytes)
  • malloc will fail by returning null, but new will throw a runtime exception

FYI: should always put a sizeof check for the malloc:

memblock = (char *)malloc( sizeof(char) * currentByteLength); 
Foo Bah
  • 25,660
  • 5
  • 55
  • 79