C4Swimmers Newsletter  

Never mix malloc with delete OR new with free

Never mix malloc with delete OR new with free as the outcome will be undefined behavior. It is not a good programming practice.

Let's look at the two undefined behavior due to the mixed usage of malloc with delete OR new with free and learn how to overcome it:

* malloc with delete (attached mallocdel.cpp) - In this case, memory is allocated with malloc and it is freed using delete or delete[].
Solution: Always use malloc with free (attached mallocfree.cpp) to overcome undefined behavior problem.

* new with free (attached newfree.cpp) - In this case, memory is allocated using new and it is freed using free.
Solution: Always use new with delete (attached newdelete.cpp) to overcome undefined behavior problem.

Note: Never mix malloc with delete OR new with free instead always use free with malloc and new with delete or delete[].

Few useful external links related to this article:
To new is C++; To malloc is C; To mix them is sin

Memory Allocation Conflict - bad free OR bad delete

Can I use delete with malloc'ed items?