<p>I see in C++ there are multiple ways to allocate and free data and I understand that when you call <code>malloc</code> you should call <code>free</code> and when you use the <code>new</code> operator you should pair with <code>delete</code> and it is a mistake to mix the two (e.g. Calling <code>free()</code> on something that was created with the <code>new</code> operator), but I'm not clear on when I should use <code>malloc</code>/ <code>free</code> and when I should use <code>new</code>/ <code>delete</code> in my real world programs.</p>

<p>If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.</p>

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 its
constructor called
.  The
```
new
```
keyword is also more
type-safe
whereas
```
malloc
```
is not type-safe 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
```
```