简体   繁体   中英

What happens, when changing ptr which is pointing to allocated memory using operator new to some other memory?

#include <iostream>
using namespace std;
int main()
{
int a = 10;
try
{
    int *p = new int;
    cout<<"p is pointing to address:"<<p<<endl;
    cout<<"Value at *p:"<<*p<<endl;

    p = &a;
    cout<<"a address:"<<&a<<endl;
    cout<<"p is pointing to address:"<<p<<endl;
    cout<<"Value at *p:"<<*p<<endl;

    delete p;

    cout<<"a address:"<<&a<<endl;
    cout<<"a val:"<<a<<endl;        
}
catch(bad_alloc &e)
{
    cout<<e.what()<<endl;
}
    return 0;

}

In the above example, the address pointed by p is changed to &a. By calling delete, logically the referent of p (deleted the thing pointed to by p) as p is pointing to address of a, now the a's address should be released to the heap.

I m curious to know about, 1. what will happen to the memory allocated by new? will it result in memory leak? 2. Even though this seems to be silly, (any way no harm in registering my thoughts) Will the compiler have any knowledge about the address pointed by p and delete exact address allocated by operator new?

In your example when you do delete you are trying to delete a stack variable which will give undefined behavior.

The original int that p pointed to is lost and is leaked. That piece of memory will remain lost until the program exits.

The compiler doesn't keep tabs on your memory or any other runtime functions, it just translates your program (your wishes) to machine code.

You know that this:

int *p = new int;

will allocate memory for an integer on the heap and it's address will be stored in p .
Now, when you say this:

p = &a;

that address is overwritten by the address of a ie p now contains the address of a and the address of the integer allocated on the heap is gone .

That memory is now leaked .

When you say:

delete p;

it is dangerous because p points to a variable on the stack .

And here is why you should not do that.


Credit of the link goes to chue x for his comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM