views:

180

answers:

4

This question was asked to me in an interview:

In C++,

  1. what if we allocate memory using malloc and use delete to free that allocated memory?
  2. what if we allocate the memory using new and free it using free?

What are the problems that we would face if the above things are used in the code?

My answer was there is no difference. Was I right in saying so?

+7  A: 

If you do so you will run into undefined behavior. Never try that. Although new might be implemented through malloc() and delete might be implemented through free() there's no guarantee that they are really implemented that way and also the user can overload new and delete at his discretion. You risk running into heap corruption.

Other than that don't forget that when you call malloc() you get raw memory - no constructor is invoked - and when you call free() no destructor is invoked. This can as well lead to undefined behavior and improper functioning of the program.

The bottom line is... never do this.

sharptooth
A: 

1) Undefined behaviour but will probably "work" though. Destructors will get called on the memory being freed that pobably doesn't want to be deconstructed.
2) Undefined behaviour but will probably "work" though. Destructors will NOT get called.

ie IF it works, and there is no guarantee of that, then it will only, likely, work exactly as required for basic builtin data types.

Goz
+3  A: 

This FAQ answers these exact questions.

Naveen
It’s rather the answer to the following question that answers this one.
Gumbo
A: 

Start by thinking about the question until you fully understand it. Then think about possible answers. When you have an answer, ask yourself if it really answers the question.

"There is no difference" does not answer the question "What are the problems ...?". If I had interviewed you, I would have made a second try to get an answer to my question.

There is no difference can mean that both points work fine (false) or that both points result in undefined behaviour (true). The other posters already gave correct answers to your interview question itself.

Peter G.