guieut
guieut

Reputation: 3

C++ members available after deletion?

I compiled & ran the code pasted below and surprisingly it worked without errors. (g++/linux) How can a deleted object have some members still available ? Is it a normal behaviour ?

#include <iostream>

using namespace std;

class chair {
    public:
    int height;
    int x;
    int y;

    chair() {
        before = last;
        if(last!=NULL)
            last->after = this;
        else
            first = this;
        last = this;
        after = NULL;
    }

    ~chair() {
        if(before != NULL)
            before->after = after;
        else
            first = after;
        if(after != NULL)
            after->before = before;
        else
            last = before;
    }

    chair* before;
    chair* after;
    static chair* first;
    static chair* last;
};
chair* chair::first;
chair* chair::last;

int main() {
    chair *room = NULL;
    int tempx = 0;
    int tempy = 1;

    while(tempx<=3) {

        tempy = 1;
        while(tempy<=3) {
            room = new chair();
            room->x = tempx;
            room->y = tempy;
            tempy++;
        }

        tempx++;
    }

    room = chair::first;
    while(room!=NULL) {
        cout << room->x << "," << room->y << endl;
        delete room;
        room = room->after;
    }
}

Upvotes: 0

Views: 224

Answers (3)

GWW
GWW

Reputation: 44093

What you are doing is undefined behavior you are accessing a deleted object. The data you are looking at is still available and the area of memory where that information is stored hasn't been overridden yet but nothing is stopping that from happening.

Upvotes: 12

Joe
Joe

Reputation: 3761

By calling delete you are simply telling the program that you don't need that block of memory anymore. It then can go and use that memory however it wants, in your case it didn't need that memory just yet so it left it as is. Later on your program might use that block of memory and you will get garbage data if you continue to access it.

http://en.wikipedia.org/wiki/Delete_%28C%2B%2B%29

Upvotes: 1

sth
sth

Reputation: 229603

delete doesn't change the pointer variable itself, so it still points to the old memory location.

You can try ro access that memory location, but if you will find something useful there after the object that lived there got deleted, depends on how lucky you are. Generally it's undefined behaviour.

Upvotes: 2

Related Questions