views:

4708

answers:

9

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

Related (duplicate?): In what cases do I use malloc vs new?

+32  A: 

The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.

Trap
Strictly speaking, the new operator just allocates the memory. It is the new expression which calls the new operator, then runs the constructor in the allocated memory.
Don Wakefield
Another difference is where the memory is allocated. I recently saw somewhere that malloc/free operate on the heap, while new/delete operate in another area of memory whose name eludes me now. (Suffice it to say, though, that other area can probably be thought of as another heap.)
RobH
RobH - all memory is allocate don the heap. Local variables are on the stack. 'new' and malloc are normally the same function except for the subsequent calling of the ctors.
Martin Beckett
@mgb: Yes you are correct that objects are allocated on either the "Application heap" or stack. __But__ @RobH is referring to what the standard calls different parts of the "Application Heap". There is the "Heap" which is where malloc allocates memory from and "Free Store" where new allocates memory from. Though in __some__ implementations these areas do overlap (this is an implementation detail).
Martin York
You statement is 100% correct but just doesn't answer the question asked, see the answer below, there is a reason why it more votes than yours.
Murali
Here's an extended version of my answer so you can understand: "The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory, [as opposed to malloc/free which do not call ctors/dtors]" I'd say that a single downvote (yours), 30 upvotes and 2 revisions still qualifies as a good answer, which means that most of people understand it. And yes, the reason is that Martin's answer is better than mine (it has 14 revisions) Btw, I also upvoted his.
Trap
All I was trying to say was there should be at least some mention of malloc/free for it to qualify as a comparison which your answer lacked. Nevertheless, it is a relevant and accurate statement, so the upvotes, I hope you understand my point. Anyway, if only SO allowed me to take my downvote back, I wholeheartedly would.
Murali
@wizard. Your down vote got me a gold badge so I am fine. Anyweay I like the succinct answer to be the first one. If people need more information they can scroll down.
Martin York
+5  A: 

new calls the ctor of the object, delete call the dtor.

malloc & free just allocate and release raw memory.

James Curran
+3  A: 

In C++ New/Delete call the Constructor/Destructor accordingly.

Malloc/Free simply allocate memory from the heap. New/Delete allocate memory as well.

Encryptic
+1  A: 

new/delete is C++, malloc/free comes from good old C.

In C++, new calls an objects constructor and delete calls the destructor.

malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.

Treb
Anybody care to explain the downvote? If my answer is wrong, please tell me.
Treb
"Coming from the dark ages before OO" sounds like you're implying that new/delete are *better* than malloc/free when in reality, neither is better or worse, they just have different uses. Note that I'm not the ont that downvoted you, I'm just guessing.
Graeme Perrow
+2  A: 

New and delete are C++ primitives which declare a new instance of a class or deletes them (thus invoking the destructor of the class for the instance).

malloc and free are C primitives and they allocate and free memory blocks (in size).

Both use the heap to make the allocation. Malloc and free are nontheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).

Jorge Córdoba
new in C++ doesn't declare an instance of a class. It (usually) allocates one from the heap, and it doesn't declare anything. You can declare an instance just by declaring it, in which case it will be on the stack, or in globals, depending on the storage duration of the declaration.
Steve Jessop
Well, it allocates the memory space for the class but you can't "declare" a class in the stack, not in the real sense of storing the class in the stack. The declaration involves just the pointer to the class which is always allocated in the stack the actual memory holding the class is in the heap.
Jorge Córdoba
Yes you can. According to the question tags this is C++, so objects can go on the stack. And new isn't a declaration, it's an expression. Declaring something and allocating it are separate things.
Steve Jessop
A: 

malloc/free is C.
new/delete is C++.

Salvatore Iovene
There's a lot more to the difference than just that.
Graeme Perrow
I'd say that is probably the most significant difference ;)
Bobby Jack
malloc/free are functions, not "C". They can be called from assembly language, for example, and even C++ code. new/delete are C++ operators.
strager
+1  A: 

The only similarities are that malloc/new both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.

However, new/delete perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/free only ever allocate and free memory.

In fact, new is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new does.

Steve Jessop
+82  A: 

new/delete

  1. Allocate/release memory
    • Memory allocated from 'Free Store'
    • Returns a fully typed pointer.
    • new (standard version) never returns a NULL (will throw on failure)
    • Are called with Type-ID (compiler calculates the size)
    • Has a version explicitly to handle arrays.
    • Reallocating (to get more space) not handled intuitively (because of copy constructor).
    • If they call malloc/free is implementation defined.
    • Can add a new memory allocator to deal with low memory (set_new_handler)
    • operator new/delete can be overridden legally
    • constructor/destructor used to initialize/destroy the object

malloc/free

  1. Allocates/release memory
    • Memory allocated from 'Heap'
    • Returns a void*
    • Returns NULL on failure
    • Must specify the size required in bytes.
    • Allocating array requires manual calculation of space.
    • Reallocating larger chunk of memory simple (No copy constructor to worry about)
    • They will NOT call new/delete
    • No way to splice user code into the allocation sequence to help with low memory.
    • malloc/free can NOT be overridden legally

Technically memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation details, which is another reason that malloc and new can not be mixed.

Martin York
Don Wakefield
A similar fact is true of new for an array of char or unsigned char: C++ standard, 5.3.4-10, and obviously any new is aligned for the type of the object being allocated (5.3.4-14).
Steve Jessop
Too bad the two lists are not side by side, in a table-like way, to help compare the features. Is there a way to do that in StackOverflow?
paercebal
Allocating arrays in C is best acheived via the `calloc()` function, not by calculating the space requirement yourself.
gnud
+1 Most complete answer I've seen yet.
Chris Ballance
Funny that they both allocate/release memory is the first difference!!
Murali
Heath Hunnicutt
@Heath: The 'Heap' and 'Free Store' are defined in the C/C++ standards respectively. They are names of areas where free memory is allocated from. Wheather the two areas are the same is an implementation detail left upt the compiler. The term 'Free Store' was introduced into the standard to deferantiate it from the 'Heap'. Note: 1) Correct I don't mean binomial store so why bring it up. 2) Using #define to overide malloc() is not legal (as defined by the standard).
Martin York
Then my nit-pick is with the standards with regard to confusing those two terms as if they meant specific free store implementations. In general, when not in a specific language context, people say "heap" to mean "free store." I bring up binomial heap because that implementation of an early free store lead to the conflation of the terminology.
Heath Hunnicutt
Re, point 2, that is interesting. Where does the standard state that?
Heath Hunnicutt
@Heath: My nit-pick with you is: You are nit-picking over well defined terms given the context. Since we are definately talking about a specific language (C++) this use of Heap/Free Store are well defiend (by the standard) and there is no confusion (with people that have read the standard). Also note: The standard does not define any implementation stratagies/techniques it defines requirements (as a standard should) it is up to the individual implementations to define the techniques used.
Martin York
Martin, way to make it personal!!! Regarding the reservation of symbol names, that is what I was afraid you meant. Nothing prevents the user of the compiler from wrapping malloc() with #define, correct?
Heath Hunnicutt
@Heath: That and another million ways. But because malloc is a reserved name, using a macro to redefine malloc is thus not allowed. Thus as noted above: __10.malloc/free can NOT be overridden legally__. PS I don't see any personal diggs above.
Martin York
Not overridden by whom? I have overriden it about 12 times and I am pretty sure I didn't violate a language standard. But then, I was not vending a language implementation at the time. I think your point in the 'answer' is a little overbroad. It cannot be overriden by an implementation, but anybody can #define a malloc wrapper. This has attendant technical weakness, vis. the legal syntax "(malloc)()" but awareness of this distinction allows a flexible, one-deep, 'extension' mechanism that is built in to the language.
Heath Hunnicutt
Martin, I see that is really what you think the standard says. I don't think section 7.26 means what you say you think it means. Using #define to change the translation pass wouldn't cross 7.26 because nothing would have changed about the definition of external names. How does using #define to wrap malloc (as a user, not a compiler vendor) change the declaration of any external names?
Heath Hunnicutt
Re making this personal, you wrote, "My nit-pick with you is..." and it does seem like that is the case.
Heath Hunnicutt
Some additional remarks: the C9x ISO C standard may be the newest pieces of paper, but it is of questionable relevance. Show me a compiler which meets it if you wish to debate this point. The C9x ISO standard is an attempt to push the C language in a direction that body wants to see it go. I would consider the ANSI standard much more relevant.Even stuck with this ISO standard, section 7.1.6 gives enough background that you can read that and clear up any confusion as to whether #define creates a "user-supplied external name." Of course it does not.
Heath Hunnicutt
Oh. Section 7.1.4 explicitly states that even the implementation may use #define as the <code>implementation</code> of the library function. I wonder if you see how that tosses a spanner in both our works. In the case where a vendor has not implemented malloc and that entire API with a #define, then the user can override it with a #define, iff user has access to all source code, source code never passes malloc as function pointer, malloc never appears in parentheses unintentionally. I'm not saying "#define malloc(s)" is a great extension mechanism, but the absolute statement "cannot be"..
Heath Hunnicutt
@Heat: I was using your own words. So don;t complain to me about it.
Martin York
@Heath: I don't care which standard you use they all say the same thing on this point.
Martin York
@Heath: Of course the implementation can use #define to define malloc. How the implementation defines malloc is implementation defined.
Martin York
@Heath: None of this changes my argument. Which is that modifying reserved names is not legal. See Section __1: NameSpace__ of the standard. <quote>Strictly conforming programs may not define any names unless they are in the user’s namespace.</quote>. Note malloc is a reserved named and thus part of the implementation namespace (not the user namespace). How the implementation defines it is irrelevant. The fact that it can use macros just makes user defined macros all the more dangerous and un-portable.
Martin York
@heath: The whole concept of namespaces was added explicitly to make what you are trying to do illegal. The problem steamed from developers using names in their program that clashed with the implementation. The issue was resolved with the concept of user defined names and implementation reserved names. A programmer (unless building an implementation (compiler/standard lib)) is only allowed to define names in the user namespace, doing otherwise is a non conforming program and thus has undefined behavior. Just because you can do it (and we all have) does not make it legal.
Martin York
@Heath: The only person that has used the phrase __"cannot"__ is you. All I have said it is __not legal__ to do so.
Martin York
@Heath: This article is over 1.5 years old. If I were wrong you don't think somebody smarter than you and I would have picked up on it by now? There are a whole bunch of people that know what they are talking about: http://stackoverflow.com/badges/49/c at SO that would never let such a high scoring article get away with any kind of misinformed statement.
Martin York
"You were using my words." -- That's dishonest. I said I had a nit-pick, not a nit-pick with YOU. In fact I meant I had some nit-picks with your answer.
Heath Hunnicutt
A question about the free store and the heap being "different": If new() is implemented by calling malloc(), does the memory returned come from the heap, or from the free store?
Heath Hunnicutt
@Heath: There is nothing in the standard that says the "Heap" and "Free Store" can not implemented as the same space. As noted above that is an implementation detail. In the sitaution where new is implemented via malloc() (a common and valid implementation) then both the Heap and "Free Store" are the same area. In implementations where new is not implemented via malloc they are distinc areas.
Martin York
But what would you name the region used in that case? Heap? or Free Store?
Heath Hunnicutt
A question about #define: If I write #define malloc(s) (myMalloc(s)) does that introduce a new name to any namespace, or change the external namespace or the declaraion of malloc()?
Heath Hunnicutt
The preprocessor doesn't define names. For (2) you have a reference to where that is stated?
Heath Hunnicutt
Even straight-jacketed in the standard you choose to believe, check out section 7.1.3, paragraph 3. Since malloc does not begin with an underscore followed by a capital letter, if the implementation #defines it, I am allowed to #undef it. Notice how specific paragraph 3 is that only the "first group above" may not be #undef'd.
Heath Hunnicutt
So there are two cases the implementation can use for its malloc: it either #defines it or it doesn't. If it does, by 7.1.3 para. 3 I am allowed to #undef that. If it does not, then my #define is nothing more than a change to the translation pass, not the namespaces. Perhaps, if we are willing to accept the fantasy of such implementations that #define malloc(), it could be stated that "overriding malloc/free is not portable." rather than "not legal."
Heath Hunnicutt
You know, having kept reading, considering what 7.1.4 para 4 says, it seems the portable solution is simple: #ifdef malloc #undef malloc #endif #define malloc(s) (myMalloc(s)) Again, what happens with #define happens at the pre-translation phase, so no such thing as "namespace" yet exists. Obviously one must not #include files which contain declarations for or definitions of malloc, subsequent to use of my suggested preprocessor command/macro sequence.
Heath Hunnicutt
I hit a nerve when I accused you of attempting to scare programmers from C to C++? Or you can't respond to points taken from your own reference?
Heath Hunnicutt
Do you think namespaces exist during the pre-processing phase? I really don't want to have the last word here. If you decide to bow out, I will consider that your defensiveness, at least. The fact that you call overriding malloc "not legal" in boldface is so lame.
Heath Hunnicutt
If I were to choose the standard, I have noticed that ANSI C is widely implemented. Of course, being an American National Standards Institute standard, it cannot be used in Europe, darn. However, you will note that I battled you within C99 and even in that document, I think you are wrong. The pre-processor is a phase of translation that precedes the creation of namespaces, full stop.
Heath Hunnicutt
In fact, even after one #define malloc(s), the external name malloc is obviously still where it began -- one can reach it with (malloc)(s) to subvert the pre-processor by ensuring the function term is evaluated as an expression during translation, which occurs after pre-processing.
Heath Hunnicutt
Can you be more specific as to why there is "no portable way of doing the re-definition"? Considering that (malloc)(s) will resolve to the "original" malloc, are you sure that the external name has been changed?
Heath Hunnicutt
I am not confusing the abstraction of an internal namespace with C++ namespaces, thanks, though. What I am saying is that the C pre-processor executes in a phase where no internal namespace exists. The C pre-processor is better compared to Emacs search-and-replace. At the time of macro substitution, the compiler has not yet been invoked. The result of #define macro is that the compilation phase will not see the token "malloc" where it previously would have. Nonetheless, the name malloc, reserved and so forth, is still available as (malloc)().
Heath Hunnicutt
http://stackoverflow.com/questions/2268149/is-the-following-program-a-strictly-conforming-c99-programYou might feel like chiming in.
Heath Hunnicutt
Removed all notes about re-defining malloc: It is now clearly answered in http://stackoverflow.com/questions/2268149/is-the-following-program-a-strictly-conforming-c99-program that it is illegal (or undefined behavior).
Martin York
+1  A: 

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

DanJ