Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Cleared Memory still accessible

I have a question about why I can access certain pieces of memory, and I think it has to do with the way I understand (or don't understand) how the compiler saves things in memory. This is the sample code I'm working with:

The header file:

#include <iostream>
using namespace std;

class A
{
public:
int value;
A (int newValue = 5)
{
    value = newValue;
    cout << "A()" << endl;
}
~A() { cout <<"~A()" << endl; }
void func1() {cout << "A::func1()" << endl; }

};


class B : public A
{
public:
B() { A::value = 0; cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
virtual void func1 () { cout << "B::func1()" << endl; }

};

class C : public B
{
public:
C() { cout << "C()" << endl; }
~C() { cout << "~C()" << endl; }
virtual void func1() { cout << "C::func1()" << endl; }
};

The .cpp file:

int main()
{
int i;

cout << endl;
A* pA = new A (5);
B* pB = new B;
C* pC = new C;

pA->func1();
pB->func1();
pC->func1();

delete pA;
delete pB;
delete pC;

cout << endl;

    //here is my first question - why don't I get a compiler error here?
    //why does the compiler know what this is? Didn't I delete it?
A* ppA = pC;

    //here is my second question - why does this work?  
    //didn't I clear this memory?
ppA->func1();
B bObject;
B* ppB = &bObject;
ppB->func1();


cin >> i;

    return 0;
}

My questions are right there in the comments - why am I not getting errors on those lines?

If I change the .h file such that func1() is virtual in A as well, I do get an access violation on that line, but still no compile-time errors.

Thanks for any explanations :)

like image 374
BIU Avatar asked Jul 12 '26 21:07

BIU


1 Answers

The compiler doesn't track whether a pointer is pointing to a legitimate object. That's a complex analysis that wouldn't even be possible in most common cases. That's why it doesn't generate an error when you assign a deleted pointer to another pointer.

Deleting an object doesn't automatically clear the memory the object used to occupy. It will get overwritten at some indeterminate point in the future, so you should never rely on it staying around. This is called undefined behavior, and one of the hallmarks of undefined behavior is that it might appear to work even when it shouldn't.

like image 184
Mark Ransom Avatar answered Jul 15 '26 10:07

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!