views:

5257

answers:

10

I am new to C++ programming but have a solid background in C#, Java and PHP. I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (eg. calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc/free and when I should use new/delete in my real world programs.

If anyone is a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.

+39  A: 

Unless you are forced to use C, you should never use malloc. Always use new. If you need a big chunk of data just do something like:

char *pBuffer = new char[1024];

Be careful though this is not correct:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

Instead you should do this when deleting an array of data:

//This deletes all items in the array
delete[] pBuffer;

The new keyword is the C++ way of doing it, and it will ensure that your type will have their constructor called. The new keyword is also more type safe whereas malloc is not typesafe at all.

The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc. The realloc function might be able to extend the size of a chunk of memory for you more efficiently.

It is worth mentioning that you cannot mix new/free and malloc/delete.

Note, some answers in this question are invalid.

int* p_scalar = new int(5);//Does not create 5 elements, but initializes to 5
int* p_array = new int[5];//Creates 5 elements
Brian R. Bondy
With regard to calling delete foo when you should call delete []foo, some compilers will fix this automagically for you and not leak and other will only delete the first entry and leak. I had a few of these in some code and valgrind will find them for you.
KPexEA
I verified this many years ago on VC++ with an array of objects and putting a breakpoint in my destructor. Only the first one got deleted. But ya, good point on some compilers catching this for you.
Brian R. Bondy
I don't think there's any memory leak if you don't use the [] syntax. But, only the destructor for the first array item will be called.
Ferruccio
If your compiler doesn't auto convert your delete to delete[] then there is definitely a memory leak.
Brian R. Bondy
If you do not use the correct delete **the result is undefined**. It's incorrect. The fact that it might get part of the thing right or work sometimes is just blind luck.
Michael Burr
I don't think it will cause heap corruption, it will just see it as an pointer to a single element.
Brian R. Bondy
See items 16.12, 16.14, and 38.7 in the C++ FAQ: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12 http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.7
Michael Burr
@KPexEA: Even if some compilers might fix your mistakes, it's still wrong to make them in the first place :) Always use delete[] where appropriate.
korona
"Unless you are forced to use C, you should never use malloc. Always use new."Why? What is the win here? For objects we need construction, but for memory blocks, you clearly document two ways to make coding mistakes (the more easily caught () vs [] in new and the less easily caught mismatched array vs scaler new and delete). What is the motivation for using new/delete for blocks of raw memory?
Ben Supnik
+9  A: 

Use malloc and free only for allocating memory that is going to be managed by c-centric libraries and APIs. Use new and delete (and the [] variants) for everything that you control.

dmckee
Also notice that well written C library will hide malloc and free internally, this is how the C programmer should work.
Dacav
A: 

If you have C code you want to port over to C++, you might leave any malloc() calls in it. For any new C++ code, I'd recommend using new instead.

Fred Larson
A: 

I'd just like to add a reminder that you cannot mix the two styles - that is, you cannot use new to create an object and then call free() on it, nor attempt to delete a block allocated by malloc().

Probably obvious to say it, but nonetheless...

nsayer
+4  A: 

Always use new in C++. If you need a block of untyped memory, you can use operator new directly:

void *p = operator new(size);
   ...
operator delete(p);
Ferruccio
interesting, i always just allocated an array of unsigned char when i need a raw data buffer like this.
Greg Rogers
Careful the semmantics should be like this: p_var = new type(initializer); Not size.
Brian R. Bondy
Not if you call operator new directly, then it takes the number of bytes to allocate as a parameter.
Ferruccio
Hrm not sure, I've never heard of this syntax.
Brian R. Bondy
@Greg - either way works the same. I just like the fact than calling operator new emphasizes that I'm doing a low-level untyped allocation.
Ferruccio
The opposite of `operator new` is `operator delete`. It is not a well defined action to call `delete` on an expression with type `void*`.
Charles Bailey
Marked down until you change 'delete p' to 'operator delete(p)'
James Hopkin
A: 

Good answers, all I have to add (that I haven't seen) is that new/delete calls the constructor/destructor for you, malloc/free does not.

Just a difference worth mentioning.

Bill K
+1  A: 

The original poster (or an editor) keeps removing my comment.

This was marked as offensive because the title and question were edited to this:

http://img371.imageshack.us/my.php?image=sofk9.jpg

Considering the profile of the original poster, I suspect he is the guilty person.

ilitirit
I think his account was deleted or closed.
Brian R. Bondy
... as you can't click on his name anymore.
Brian R. Bondy
+2  A: 

Reason for downvotes and offensive reports: Twice he edited his post to delete all text and replaced it with cuss words. Then minutes later he rolled it back to the original question.

Also, some people left comments explaining their downvotes, but they have been mysteriously deleted.

davr
+12  A: 

From the C++ FQA Lite:

[16.4] Why should I use new instead of trustworthy old malloc()?

FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class.

FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe").

Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something.

Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.

Sorry, I just couldn't resist. :)

Matthias Benkard
That is a *riot*! Thanks.
dmckee
A: 

The new and delete operators can operate on classes and structures, wheres malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

selwyn