dimanche 26 septembre 2021

Why access deleted pointer won't crash the program?

#include <iostream>
#include<list>

using namespace std;
template <class T>
class Ptr {
public:
    Ptr() {
        a = nullptr;
        l.push_back(0);
    }

std::list<int> l;
void print_this() {
    cout<<this<<endl;
}

protected:
    int *a;
};

int main()
{
    Ptr<int> *ptr = new Ptr<int>();
    delete ptr;
    //ptr = nullptr; //if uncomment this line will crash
    auto p = &(ptr->l);  
    cout<<"p is "<<p<<endl;
    ptr->print_this();
    ptr->l.push_back(1);
    cout<<"size is "<<ptr->l.size()<<endl;
    cout<<"end";
    return 0;
}

I run code here: https://www.programiz.com/cpp-programming/online-compiler/ output is :

p is 0x5628eb47deb0
0x5628eb47deb0
size is 2
end

if I set ptr to nullptr after delete, it will crash at push_back. But still fine when I access the list.

How is it even possible that I push data to a dangling pointer without crashing it??

Aucun commentaire:

Enregistrer un commentaire