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.
CodePudding user response:
sizeof(p)
is the size of void*
, the size of a pointer to void
. It is not the size of the block of memory to which this pointer is pointing, that is sizeof(Person)
.
A void*
alone carries no information on the size of the pointee. Though, in the background free
"knows" how big is the memory block associated with p
because you specified the size when you used malloc
. If you would implement your own memory managment rather than falling back to free
/malloc
(eg you could use a memory pool that uses some big block of preallocated memory) then you would need to implement such mapping from pointer to size of the memory block as well.
CodePudding user response:
when you print out the size of the p which is a void pointer it contains an address which is freed and the address is exactly 4 bytes long.