When, if ever, can delete and free be used interchangeably in C++?
My concern is as follows: Say there is an incorrect mixup in the use of malloc/ free and
new/ delete (not to mention new[]/ delete[]). However delete and free doing the same thing;
Fortuitously so this goes uncaught in testing. Later this may lead to a crash in production.
How can I enforce some kind of check to prevent this? Can I be warned if the two are mixed up?
If not at compile time, perhaps some code instrumentation at run time? How would I approach
this?
The intention of this question is to find ways to avoid inadvertent mix up in the usages.
To answer the second question, if you control both
malloc/freeandoperator new/delete, you can stash extra information to associate with pointers returned by both that tell you how they were allocated. When a pointer is passed tofreeoroperator delete, check to see that it was allocated by the appropriate function. If not, assert or raise an exception or do whatever it is you do to report the mismatch.Usually this is done by allocating extra memory, e.g., given
malloc(size)oroperator new(size), you allocatesize + additional spaceand shove extra information in there.