First, it might help to understand what happens behind the scene before discussing if
is to be called.
malloc simply acquires some memory and returns the address to it.
malloc and in addition, initializes the memory with 0.
malloc and then calls the constructor code of the respective type.
free marks the memory block at the given address to be free for being used by some other entity.
delete calls the destructor code of the static type (or the polymorphic type if the destructor of the static type is virtual) and finally calls
free on that memeory.
For POD types it doesn't hurt if you call
, since the constructor/destructor is trivial, i.e. the constructor might initialize memory and the destructor doesn't do anything).
For non-POD types, I would say, it is a programming mistake in C++ if you use
: if the constructor/destructor was trivial, you don't gain anything, if it was not trivial, you break the logic of the program.
Whichever way you did acquire memeory, normal application and library implementation never
get into the situation where it matters if you have to call delete or not, unless you have
or you work on raw memory (
you must free memory(?!).
If you want to check if a C++ program is correct regarding malloc/free versus new/delete, then the issue is very simple: No C++ uses ever malloc/free
. If you have any C-code in C++ program, segregate it from the rest and skip that part from the check (and write a fascade towards C++ so that this C-resource never get washed directly into the C++ code).
BTW: the undelying memory management in C/C++ is a matter of the Operating System. I've seen some OS that acquires for each malloc some more bytes for the book keeping (memory size and if it is an array or a single entity). That block is usually just before the memory adderess that is returned to the client code.