0

In a recent interview, the interviewer asked me if we can use free() to deallocate space which was previously allocated using new. I answered in a yes. :|

I know the pair works like malloc() - free() & new - delete.

  • But since both utilizes some pointer mechanisms, then what is wrong in intermixing them?

  • There must be a possibilty to achieve deallocation while intermixing the two pairs. Is it possible? Even in theory? And what could be the possible scenarios to intermix them?

  • If doing the previously stated point is possible, then why have we introduced delete with new?

Kindly enlighten me on this subject & if there's any source code of new/delete/malloc/free available to you or any thorough guide to grasp this particular topic, please provide the link.

  • My another curiosity is,  what could be the caveats & problems with delete?
WhiteSword
  • 101
  • 9
  • Yup, but doesn't cover the last point. And the possible scenarios to use them. – WhiteSword Aug 26 '16 at 05:44
  • 1
    [What is the difference between new/delete and malloc/free?](http://stackoverflow.com/a/240308) This is covered extensively in this and other questions that can be easily looked up. – Basilevs Aug 26 '16 at 06:13
  • Also consider the difference between `delete` and `delete[]`. – cdarke Aug 26 '16 at 07:09

1 Answers1

1
  1. For one thing, they may be using completely different heaps. In more than one application of ours the global new and delete are redefined to perform some additional bookkeeping; if you pass to free a pointer returned by new it won't be recognized as stuff from malloc, because we are keeping extra info at the start of each memory block. The standard library can do the same.
  2. Why should there be? As already said, the memory they return can come from different heaps, so it makes no sense to use one to deallocate stuff from the other. Now, if you are allocating POD types and if the global new operator is just a thin wrapper around malloc, in theory it could accidentally work to use freefor memory allocated with new, but I really don't see the point in doing so besides adding confusion (and potential undefined behavior).
  3. new and delete were introduced as operators to deal with non-POD types. If all you want is "raw" memory malloc (or, in general, a single function) is fine, but if you want to allocate objects stuff gets more complicated; the allocation mechanism must be aware of the type of the allocated data, not just of the required size, because it has to invoke the constructors (the same for delete, which has to invoke destructors, although new could have just saved the function pointer to the destructor).
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299