3

class sphere {
    int radius;
    public:
        sphere(int r){
        radius = r;
        }
        void setRadius(int r) {
        radius = r;
        }

        int getRadius() {
        return radius;
        }
};

int main()
{
    sphere *a, *b;
    a = new sphere(1);
    b = a;
    delete b;
    cout << a->getRadius() << endl;
    return 0;

}

This code actually prints out 1 on the console. According to this post, the sphere with radius 1 should have been deleted.

My question is:

Why is it not returning a SegFault? I am expecting a SegFault because since the sphere is deleted, ->getRadius wouldn't be available for a anymore.

jess
  • 41
  • 3
  • 5
    Undefined behavior comes with no guarantee whatsoever, not even a segfault. It might cause a segfault or something completely different on another compiler, another machine or simply when you run it again. There's no use trying to figure out why undefined behavior does something instead of something else - just avoid undefined behavior. – Blaze Oct 08 '19 at 07:49
  • A crash is only one possible symptom of undefined behaviour, not a guaranteed outcome. The call of `a->getRadius()` has undefined behaviour. Undefined behaviour doesn't prevent the appearance that a deleted object still exists. – Peter Oct 08 '19 at 07:55
  • FWIW, if you google the exact question title (with "C++" added) you get many stackoverflow results answering your question. The stackoverflow search is terrible in comparison, I do not recommend it. – Max Langhof Oct 08 '19 at 07:56
  • No need to use two pointers. `delete` does not modify its "argument" any way. – Daniel Langr Oct 08 '19 at 08:00
  • Try creating another sphere with a different value, e. g. 7, and assign it to `b`. There's quite some chance that it will occupy the memory the already deleted one used previously. If so (but there's no guarantee at all!), you'll see the newly set value via `a` pointer as well... – Aconcagua Oct 08 '19 at 08:06

1 Answers1

0

Because the C++ standard doesn't require to do SegFault. It's just undefined behavior, that depends on your compiler, environment of even Moon phase

P. Dmitry
  • 1,123
  • 8
  • 26