hi
can sombody please tell me which is safer to use malloc and free functions or to use new and delete operators? and why?
Printable View
hi
can sombody please tell me which is safer to use malloc and free functions or to use new and delete operators? and why?
new and delete. They are the standard C++ operators and they are type safe compaired to malloc and free. Also with C++ you can delete a null pointer safely. free() has unpredictable results when freeing a null pointer.
Read the standard
The substantial difference is that new/delete call class constructors and destructors, and malloc/free don'tQuote:
7.20.3.2 The free function
Synopsis
[#1]
#include <stdlib.h>
void free(void *ptr);
Description
[#2] The free function causes the space pointed to by ptr to
be deallocated, that is, made available for further
allocation. If ptr is a null pointer, no action occurs.
Otherwise, if the argument does not match a pointer earlier
returned by the calloc, malloc, or realloc function, or if
the space has been deallocated by a call to free or realloc,
the behavior is undefined.