I created a class and overloaded new
and delete
operators to print the size of memory allocated/freed. In the example below, it allocated 28 bytes but frees 4 bytes. Why?
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person() {
cout << "Constructor is called.\n";
}
Person(string name, int age) {
this->name = name;
this->age = age;
}
void* operator new(size_t size) {
void* p = malloc(size);
cout << "Allocate " << size << " bytes.\n";
return p;
}
void operator delete(void* p) {
free(p);
cout << "Free " << sizeof(p) << " bytes.\n";
}
};
int main()
{
Person* p = new Person("John", 19);
delete p;
}
output:
Allocate 28 bytes.
Free 4 bytes.