I came across an issue which I could not resolve.
My question is, if I used malloc
to allocate memory and then memory block is delete using delete
No, it is not a rule of thumb that you should not mix new/free or malloc/delete.
Sure, it might be possible to use free
to relinquish an allocation you obtained with new
without a crash, but it is highly implementation/system specific.
Ignoring the fact that you're bypassing destructors or writing code that will corrupt memory on some systems, the more fundamental, more basic C++ consideration is really simply this:
malloc/free are global, system functions, while new and delete are operators.
struct X {
void* operator new(size_t);
void operator delete(void* object);
};
Sure - you can borrow a book from Amazon and return it to your local library: go there late one night and leave it on their front door step.
It's going to have undefined behavior, up to and including your getting arrested - and I'm talking about mixing new/free again here :)
Put another way: malloc
and free
deal with raw memory allocations, while new
and delete
deal with objects, and that's a very different thing.
void* p = new std::vector(100);
void* q = malloc(sizeof(*q));