Lecture 2 - Code

Dangling pointer example

#include <iostream>
using namespace std;
 
int main() {
    int *a = new int;
    int *b = new int;
 
    cout << " a = " << a << " b = " << b << endl;
 
    *a = 4;
    cout << " *a = "<< *a << " *b = " << *b << endl;
    b = a;
 
    cout << " a = " << a << " b = " << b << endl;
    cout << " *a = "<< *a << " *b = " << *b << endl;
 
    delete a;
    //delete b; //dangling pointer
    b = NULL;
    delete b; 
}

Solution to memory leak

#include <iostream>
using namespace std;
 
int main() {
    int *a = new int;
    int *b = new int;
    int *c = a;
 
    a = b;
    //after this there is no pointer to memory pointed by a
 
    delete a;
    //delete b; //memory leak
    delete c;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License