Would there be any problems on calling delete on a object created by malloc()?
Thanks.
Printable View
Would there be any problems on calling delete on a object created by malloc()?
Thanks.
Yes.
Keep in mind that new and delete are operators that can be overridden. If you manuallly set your new and delete operators to use malloc() and free() then I see no problems using it. Otherwise, you are basically saying "i'm willing to bet by default my compiler's new uses malloc()" which is something you should never do ever. If you look at your header files you may find that new doesn't use malloc() (common scenario).
But even if you manually override the new operator to use malloc() and your delete to use free() that doesn't mean you are going to gain a lot of friends by having code such as:
Example A
orCode:free(new MyClass);
Example B
Oh yes, one more issue to bring up. If you are using malloc() to allocate a class or structure you are also not calling its constructor. Thus malloc() will give you an object filled with erroneous data.Code:MyClass *a = reinterpret_cast<MyClass *>(malloc(MyClass));
delete a;
>> If you are using malloc() to allocate a class or structure you are also not calling its constructor
and of course using free() to deallocate the class wouldn't call the destructor.
Ah yes, indeed thats an even bigger issue than your constructor issue. I mostly focused on his wanting to use delete and delete[] for malloc()'ed functions. I'm willing to bet his code is more like this:
Example
In which case you cannot do as you want as you can't override the global new and the global delete. In which case there would be no destructor to call. But if he is indeed using it on objects, as Sabastiani has commented, you are opening Pandora's box.Code:int *i = malloc(50 * sizeof(int));
delete[] i;
This way or that, it is a waste of time to be even talking about the possibility. Just don't do it, there's no reason to.
Well ya never know. He could be aiming for first place in a code obfustication contest. That definitely scores "what the hell?" points.