13

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?

manlio
  • 18,345
  • 14
  • 76
  • 126
Vijay
  • 65,327
  • 90
  • 227
  • 319
  • related: http://stackoverflow.com/questions/1350819/c-free-store-vs-heap – Nick Dandoulakis Jul 06 '10 at 07:08
  • 1
    I hope you answered right to the other questions – ereOn Jul 06 '10 at 07:38
  • 7
    "there is no difference." -> That is technically correct, both points lead to undefined behavior, so there is no difference :) – fredoverflow Jul 06 '10 at 07:55
  • 4
    As it was an interview question, I don't think they expected yes/no answer. You were expected to explain what malloc/free and new/delete do, how they differ, how they are used and **why** you should not mix them. This will show them that you know how C++ and C++ runtime works, how it relates to C standard library and that you can think about those issues. So, answering your question, with "answer [...] there is no difference" you failed. :-( – Tomek Szpakowicz Jul 06 '10 at 08:37
  • Read any [C++ FAQ](http://www.parashift.com/c++-faq-lite/mixing-malloc-and-delete.html). – Lundin Mar 14 '14 at 13:44
  • This [FAQ](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3) answers these exact questions. – Naveen Jul 06 '10 at 07:03

2 Answers2

14

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
  • 167,383
  • 100
  • 513
  • 979
1

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
  • 61,365
  • 24
  • 124
  • 204