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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…