Jerry Xue
Jerry Xue

Reputation: 331

C++ new operator allocate new memory

I was running a tiny program for fun and encountered a issue that puzzled me.

#include <iostream>
#include <string>

using namespace std;

struct T
{
    int val;
};
int main()
{
    for(int i = 0; i < 2; ++i)
    {
        T *p = new T;
        cout << p << endl;
        delete p;
    }

    T *q = new T;
    cout << q << endl;
    delete q;

    return 0;
}

output:

0x16b76d0
0x16b76d0
0x16b76d0

They are all at same memory location?

Upvotes: 2

Views: 663

Answers (2)

Santiago Varela
Santiago Varela

Reputation: 2237

The compiler along with your OS (Operating System) decide which memory address to allocate to your dynamically allocated memory. When delete is invoked, the memory address a pointer was pointing to is no longer referenced. Hence, the compiler can take the liberty of utilising that same memory address for your new allocations. It's not something which we have control of at this level of programming.

Upvotes: 1

Abdus Khazi
Abdus Khazi

Reputation: 483

You are deleting the memory after printing the address. Then the memory manager is free to choose the same address to allocate new memory.

Upvotes: 4

Related Questions