Search code examples
c++pointersmemory-leaksnew-operatordelete-operator

C++ Pointer after delete it then give value


I come up against with this problem, it create 3 block of memory, I'm confuse if delete the *r, is **r still exist or not? should I move **r to *r's position? do I need another "new int" statement to give value?

int t = 5;
int **r;
r = new int *;  //declare pointer  
*r = new int;
delete *r;      // delete pointer
*r = t;         //give new value

sorry for ask question with mistake. still learning in it. Thanks.


Solution

  • Your code is correct (Ideone):

    #include <iostream>
    using namespace std;
    
    int main() {
        int **r = new int *; // declare pointer to int*
        cout << r << endl;   // outputs some address in memory (pointer to int*)
        cout << *r << endl;  // outputs some garbage value
    //  cout << **r << endl; // it's invalid
    
        *r = new int;        // assign to memory pointed by r new value
        cout << *r << endl;  // outputs some address in memory (pointer to int)
        cout << **r << endl; // outputs some garbage value
    
        delete *r;           // delete pointer to int
        cout << *r << endl;  // outputs same address in memory, but we can't dereference it
    //  cout << **r << endl; // it's invalid, because we deleted *r
    
        // here you can acces r, *r, but not 
        return 0;
    }