0

Calling delete calls the destructor of a class, but calling free() does not.

Can that cause a memory leak? If not, why?

#include <iostream>
#include <cstdlib>
using namespace std;

class x{
 public:
 int a;
 ~x(){cout<<"destroying"<<endl;}
};


int main() {
  x *y = (x*)malloc(sizeof(x));
  free(y);
  x *z = new x;
  delete z;
  return 0; 
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Robert Page
  • 366
  • 4
  • 10
  • It has undefined behaviour, so it can cause anything or nothing at all. – molbdnilo Dec 11 '20 at 17:51
  • 2
    `new` *must* be matched with `delete` (and `new[]` with `delete[]`). `free` is the match of `malloc`. – Some programmer dude Dec 11 '20 at 17:51
  • 1
    That's [UB](https://en.cppreference.com/w/cpp/language/ub), see for example [Is it safe to free() memory allocated by new?](https://stackoverflow.com/questions/22406278/is-it-safe-to-free-memory-allocated-by-new). – dxiv Dec 11 '20 at 17:52
  • 1
    *After* the edit, the line `x *y = malloc(sizeof(x));` won't even compile. – dxiv Dec 11 '20 at 17:56
  • You know that [doesn't even compile?](//coliru.stacked-crooked.com/a/5d026497cb286be0) – Deduplicator Dec 11 '20 at 17:56
  • O yeah, I just saw that rn. I edited that without compiling, coz I thought that would create a new context of free with new. – Robert Page Dec 11 '20 at 17:57

2 Answers2

3

Can that cause a memory leak?

In your particular example, no. The x object is merely being allocated by malloc(). free() will correctly deallocate the memory that malloc() allocated. But the object will not be destructed, which is fine in this example because it was not constructed to begin with, so there is nothing to destruct. However, if you try to use that object in any way that expects the constructor to have run, then you end up in undefined behavior territory.

C (where malloc() and free() come from) has no concept of classes, only of memory (de)allocation. C++, on the other hand, has separate concepts of memory (de)allocation and object (de)construction, so you need to be very careful that you use them correctly and not mix them up incorrectly.

If an object were constructed via new, but then deallocated by free() rather than being destructed by delete, the code would definitely have undefined behavior, and if that object had internally allocated any additional memory for itself that the object's destructor is expected to free, that extra memory would be leaked, yes.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • http://isocpp.org/wiki/faq/freestore-mgmt#mixing-malloc-and-delete, this link might also be able to give more clarification, so im just gonna leave it here – Robert Page Dec 11 '20 at 18:18
1

Can free() cause a memory leak?

Not as such. But it can cause undefined behaviour. Of course, if the behaviour of the program is undefined, memory leak is among possible behaviour. As are all other behaviours.

eerorika
  • 232,697
  • 12
  • 197
  • 326