It's probably true that C++'s new
is safer than malloc()
, but that doesn't automatically make malloc()
more unsafe than it was before. Did your friend say why he considers it insecure?
However, here's a few things you should pay attention to:
1) With C++, you do need to be careful when you use malloc()
/free()
and new
/delete
side-by-side in the same program. This is possible and permissible, but everything that was allocated with malloc()
must be freed with free()
, and not with delete
. Similarly, everything that was allocated with new
must be freed with delete
, and never with free()
. (This logic goes even further: If you allocate an array with new[]
, you must free it with delete[]
, and not just with delete
.) Always use corresponding counterparts for allocation and deallocation, per object.
int* ni = new int;
free(ni); // ERROR: don't do this!
delete ni; // OK
int* mi = (int*)malloc(sizeof(int));
delete mi; // ERROR!
free(mi); // OK
2) malloc()
and new
(speaking again of C++) don't do exactly the same thing. malloc()
just gives you a chunk of memory to use; new
will additionally call a contructor (if available). Similarly, delete
will call a destructor (if available), while free()
won't. This could lead to problems, such as incorrectly initialized objects (because the constructor wasn' called) or un-freed resources (because the destructor wasn't called).
3) C++'s new
also takes care of allocating the right amount of memory for the type specified, while you need to calculate this yourself with malloc()
:
int *ni = new int;
int *mi = (int*)malloc(sizeof(int)); // required amount of memory must be
// explicitly specified!
// (in some situations, you can make this
// a little safer against code changes by
// writing sizeof(*mi) instead.)
Conclusion:
In C++, new
/delete
should be preferred over malloc()
/free()
where possible. (In C, new
/delete
is not available, so the choice would be obvious there.)