0

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.
ParsaAi
  • 293
  • 1
  • 14
  • In the delete overload, you are printing out sizeof() on a void pointer, which is why you are getting a size = 4 bytes – Ryan Kane Jul 25 '22 at 11:03
  • Newbies often think `sizeof` has magical powers. – john Jul 25 '22 at 11:08
  • 2
    Change the code to `cout << "Allocate " << sizeof(p) << " bytes.\n";` and you'll see the problem. – john Jul 25 '22 at 11:09
  • Possibly relevant question: [Determine size of dynamically allocated memory in C](https://stackoverflow.com/q/1281686/580083) – Daniel Langr Jul 25 '22 at 11:35

2 Answers2

6

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

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.

PoePew
  • 37
  • 7