ok the only reason is it may cause problem when it is used in any other compiler or version
There are two big reasons:
- The new operator calls constructors and the delete operator calls destructors. malloc() and free() only work with raw memory. So if you use malloc() to allocate objects with constructors the constructors will not be called; this will probably crash your program. Likewise if you use new to allocate objects with destructors and free() to deallocate them, the destructors won't be called; this will probably cause resource leaks.
- The data structure used to store and manage allocated memory might be different between malloc()/free() and new/delete. If you mix them, the pointer might be valid with one but not the other and your program will probably crash.
For example, on a Windows compiler the heap might be created with HeapCreate() instead of GetProcessHeap() and malloc()/free() could use a different heap object than new/delete like this:
#include <Windows.h> class memory_manager { public: memory_manager(): _heap(HeapCreate(0, 0, 0)) { } ~memory_manager() { HeapDestroy(_heap); } void *alloc(size_t bytes) { return HeapAlloc(_heap, 0, bytes); } void dealloc(void* p) { HeapFree(_heap, 0, p); } private: HANDLE _heap; }; int main(void) { memory_manager new_manager; memory_manager malloc_manager; void* p = new_manager.alloc(1); malloc_manager.dealloc(p); // Boom! }