Reputation: 361
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;
}
Upvotes: 0
Views: 624
Reputation: 238411
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.
Upvotes: 1
Reputation: 597205
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.
Upvotes: 3